Javascript find object with matching property in array of objects and get another property if exists
The smallest method is not necessarily the most efficient. I would do it this way:
let wantedProperty = (arrayOfObjects.find(obj => obj.id === wantedObject.id) || {}).title || 'None Found';
How to determine if Javascript array contains an object with an attribute that equals a given value?
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
Find object by id in an array of JavaScript objects
Use the find()
method:
myArray.find(x => x.id === '45').foo;
From MDN:
The
find()
method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefined
is returned.
If you want to find its index instead, use findIndex()
:
myArray.findIndex(x => x.id === '45');
From MDN:
The
findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
If you want to get an array of matching elements, use the filter()
method instead:
myArray.filter(x => x.id === '45');
This will return an array of objects. If you want to get an array of foo
properties, you can do this with the map()
method:
myArray.filter(x => x.id === '45').map(x => x.foo);
Side note: methods like find()
or filter()
, and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).
search for a specific property in array of objects and return boolean
You can use some
. So basically it will return a boolean value if any of the object property in array matches the required value
let arr = [{
name: "john",
age: 22
},
{
name: "george",
age: 55
}
];
let obj = {
name: "bill",
age: 55
}
const val = arr.some(item => item.age === obj.age);
console.log(val)
How to check if property of an objects of array matches with one of the values in another array of object
First off, you'll have to make sure if the ID types are correct. Users has Number type for IDs but attendingUsers has String type.
Let's say they're both the same type for the code below (I'm going with string).
You can turn the attendingUsers array into an array of strings with:
const attendingUsersIds = attendingUsers.map(attendingUser => attendingUser.id)
Then match the ids with:
const matchedUsers = users.filter(user => attendingUsersIds.includes(user.id))
If they're intended to not be the same type, you can use user.id.toString()
to turn the Number into a String or parseInt(attendingUser.id)
to turn the String into a Number.
Finding objects in array by multiple (and unknown in advance) properties
You can use filter to filter out the array.
const items = [
{
firstName: "John",
lastName: "Doe",
password: "*******",
email: "john@i.com",
role: "ROLE_ADMIN"
},
{
firstName: "Jane",
lastName: "Doe",
password: "********",
email: "jane@i.com",
role: "ROLE_USER"
},
{
firstName: "John",
lastName: "Roe",
password: "**********",
email: "johnr@i.com",
role: "ROLE_USER"
}
];
function match(params) {
const keys = Object.keys(params);
return items.filter((item) => {
let flag = true;
keys.every((key) => {
if ((item[key] && item[key] !== params[key]) || !item[key]) {
flag = false;
return false;
}
return true;
});
return flag;
});
}
console.log(match({ firstName: "John",role: "ROLE_USER" }));
Find Object with Property in Array
// this is not working - NSArray is not a subtype of Images- so what if there is only 1 possible result?
You have no way to prove at compile-time that there is only one possible result on an array. What you're actually asking for is the first matching result. The easiest (though not the fastest) is to just take the first element of the result of filter:
let imageObject = questionImageObjects.filter{ $0.imageUUID == imageUUID }.first
imageObject
will now be an optional of course, since it's possible that nothing matches.
If searching the whole array is time consuming, of course you can easily create a firstMatching
function that will return the (optional) first element matching the closure, but for short arrays this is fine and simple.
As charles notes, in Swift 3 this is built in:
questionImageObjects.first(where: { $0.imageUUID == imageUUID })
How to filter an array of objects based on another array of object's property value?
let arr1 = [
{ key: "WIHUGDYVWJ", className: "science" },
{ key: "qwljdhkuqwdnqwdk", className: "english" },
{ key: "likubqwd", className: "robotics" },
{ key: "abcd", className: "history" }
];
let arr2 = [
{ key: "WIHUGDYVWJ", title: "math" },
{ key: "qwljdhkuqwdnqwdk", title: "english" },
{ key: "likubqwd", title: "robotics" }
];
// q1 answer
console.log(arr1.map(arr1Item => arr2.filter(arr2Item => arr1Item.className === arr2Item.title)).flat());
// q2 answer
console.log(arr1.filter(arr1Item => !arr2.some(arr2Item => arr2Item.title === arr1Item.className)));
Related Topics
How to Calculate Uilabel Width Based on Text Length
iOS Keeping Old Launch Screen and App Icon After Update
Changing Vc Issue in Swift. How to Pass Data Between Views in Tab Bar Controller
What Is the '' Is or the ':' at the Equation When Coding in Swift
Developing for iOS Device in Windows Environment with Flutter
How to Remove the Default Navigation Bar Space in Swiftui Navigationview
Rsa Implementations in Objective C
Detect First Launch of iOS App
How to Change Locale Programmatically with Swift
How to Get an Iso 8601 Date on iOS
How to Change Inside Background Color of Uisearchbar Component on iOS
Drawing Class Drawing Straight Lines Instead of Curved Lines
Nsurlconnection Sendasynchronousrequest Can't Get Variable Out of Closure
How to Pass Multiple Values with a Notification in Swift