How to Find Object in Array by Property in JavaScript

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

From an array of objects, extract value of a property as array

Here is a shorter way of achieving it:

let result = objArray.map(a => a.foo);

OR

let result = objArray.map(({ foo }) => foo)

You can also check Array.prototype.map().

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 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);

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 }

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 can I get the index of an object by its property in JavaScript?

As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:

function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}

var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];

With this, not only can you find which one contains 'John', but you can find which contains the token '312312':

findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1

The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().

Accessing Object Property Values Within an Array - JavaScript

You can acces items in arrays at given position by their index. In javascript indexes of arrays are starting with 0: myArray[0]. To access the property of the returned object just use dot-notation: myArray[0].myProperty.

let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}];

console.log(object1[1].job);

How to find object in array by property in javascript?

_findItemByValue(Obj, "start", 4);

var _findItemByValue = function(obj, prop, value) {
return obj.filter(function(item) {
return (item[prop] === value);
});
}

Compatible with all except IE6, IE7, IE8, but exist polyfill.

if (!Array.prototype.filter) {
Array.prototype.filter = function (fn, context) {
var i,
value,
result = [],
length;

if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
throw new TypeError();
}

length = this.length;

for (i = 0; i < length; i++) {
if (this.hasOwnProperty(i)) {
value = this[i];
if (fn.call(context, value, i, this)) {
result.push(value);
}
}
}
return result;
};
}


Related Topics



Leave a reply



Submit