Find an Object in Array

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. Otherwise undefined 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).

Find a value in an array of objects in Javascript

You can loop over the array and test for that property:

function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

Array.includes() to find object in array

Array.includes compares by object identity just like obj === obj2, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some() instead which takes a function:

const arr = [{a: 'b'}]console.log(arr.some(item => item.a === 'b'))

ES6: Find an object in an array by one of its properties

newData.find(x => x.investor === investor)

And the whole code:

const originalData = [  { "investor": "Sue",   "value":  5,   "investment": "stocks"  },  { "investor": "Rob",   "value": 15,   "investment": "options" },  { "investor": "Sue",   "value": 25,   "investment": "savings" },  { "investor": "Rob",   "value": 15,   "investment": "savings" },  { "investor": "Sue",   "value":  2,   "investment": "stocks"  },  { "investor": "Liz",   "value": 85,   "investment": "options" },  { "investor": "Liz",   "value": 16,   "investment": "options" },];
const newData = [ { "investor": "Sue", "stocks": 0, "options": 0, "savings": 0 }, { "investor": "Rob", "stocks": 0, "options": 0, "savings": 0 }, { "investor": "Liz", "stocks": 0, "options": 0, "savings": 0 },];
for (let {investor, value, investment} of originalData) { newData.find(x => x.investor === investor)[investment] += value;}
console.log(newData);
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

Find object within array of arrays and return the array it belongs to

You'll need two loops, but you can use methods that do the iteration for you:

let array1 = [{x: 0, y: 1}, {x: 5, y: 9}, {x: 1, y: 8}, {x: 3, y: 2}];let array2 = [{x: 5, y: 4}, {x: 4, y: 5}, {x: 8, y: 8}, {x: 3, y: 2}];let array3 = [{x: 4, y: 3}, {x: 0, y: 6}, {x: 7, y: 8}, {x: 5, y: 2}];
const array = [array1, array2, array3];let obj = array2[2]; // let's find this one...
let result = array.find(arr => arr.includes(obj));
console.log(result);

Find Object inside Array inside another Array

You can first flaten this array to an array of inner objects and then use filter() or find().

let bigArray = [  {      Name: 'Trump',      children: [                   {Name: 'TrumpChild1', City: 'city1'},                    {Name: 'TrumpChild2', City: 'city2'}      ]  },  {      Name: 'Barack Obama',      children: [                   {Name: 'Barack Obama Child1', City: 'city3'},                    {Name: 'Barack Obama Child2', City: 'city4'}      ]  },  {      Name: 'Clinton',      children: [                   {Name: 'Clinton Child 1', City: 'city5'},                    {Name: 'Clinton Child2', City: 'city6'}      ]  }];
let all = bigArray.reduce((prev, next) => prev.concat(next.children), []);let result = all.find(obj => obj.City === 'city1');console.log(result);
// if there can be multiple matches then use filterlet results = all.filter(obj => obj.City === 'city1');console.log(results);

Find Object in Object Array Swift

You just need to use contains(where: method here.

if self.allFriends.contains(where: { $0.uid == uidOfLeaderBoard }) {
//...
}

How do I find the first object in an array which exists in another array using TypeScript?

Solution

const res = array2.find((o2) =>
array1.some((o1) => o1.name === o2.name && o1.lastname === o2.lastname)
);

Explanation

You don't need to use "classic" let i=0 loop techniques because you can make use of the methods Array.prototype.some() and Array.prototype.find().

We want the first element of array2 that matches a condition, so we use array2.find(), which stops as soon as any element returns true for the provided callback.


The condition we are checking for the elements of array2 is that they are contained in array1. If these were primitive values then you could use Array.prototype.includes(). More explanation of that can be found in the answers to these questions:

  • Check if an array contains any element of another array in JavaScript
  • How do I check if an array includes a value in JavaScript?

When dealing with objects, we can't rely on a strict === comparison between the two objects. That would be true if and only if the two objects are references to the same object in memory. But we want to determine that an object is "the same" if all of its properties have the same values. You could use a helper like lodash's isEqual or check out the answers to this question:

  • How to determine equality for two JavaScript objects?

Here we only have two properties which are both string so it is easy to define our own comparison check. We say that o1 and o2 match if:

o1.name === o2.name && o1.lastname === o2.lastname

We want to find() in array2 the first element where array1 contains a match. We use array1.some() to check for matches. This function returns true if any element of array1 matches the condition. It will stop as soon as it finds any true element.

const res = array2.find((o2) =>
array1.some((o1) => o1.name === o2.name && o1.lastname === o2.lastname)
);

By defining all callbacks inline we avoid the need for any Typescript types annotations.
The types of o1 and o2 can be inferred properly from the types of array1 and array2. You could break this into pieces, but you would need to write out the types for the arguments of your functions.

Typescript Playground Link

How can I find and update values in an array of objects?

You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
if(element.id === item.id) {
items[index] = item;
}
});


Related Topics



Leave a reply



Submit