Find a value in an array of objects in Javascript [duplicate]

Find a value in an array of objects in Javascript [duplicate]

This question already has an answer here:

Get JavaScript object from array of objects by value of property [duplicate]

17 answers

I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where “name” is “string 1″. Here is an example array.
var array = [
{ name:”string 1″, value:”this”, other: “that” },
{ name:”string 2″, value:”this”, other: “that” }
];

Update: I should have said this earlier, but once I find it, I want to replace it with an edited object.

Solutions/Answers:

Solution 1:

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

Solution 2:

Finding the array element:

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

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);

Replacing the array element:

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

let obj = arr.find((o, i) => {
    if (o.name === 'string 1') {
        arr[i] = { name: 'new string', value: 'this', other: 'that' };
        return true; // stop searching
    }
});

console.log(arr);

Solution 3:

In ES6 you can use Array.prototype.find(predicate, thisArg?) like so:

Related:  Is it possible to use ES6 in a Chrome Extension?
array.find(x => x.name === 'string 1')

http://exploringjs.com/es6/ch_arrays.html#_searching-for-array-elements
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

To then replace said object (and use another cool ES6 method fill) you could do something like:

let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);

Solution 4:

As per ECMAScript 6, you can use the findIndex function.

array[array.findIndex(x => x.name == 'string 1')]

Solution 5:

with underscore.js use the findWhere method:

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


var result = _.findWhere(array, {name: 'string 1'});

console.log(result.name);

See this in JSFIDDLE

Solution 6:

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

var foundValue = array.filter(obj=>obj.name==='string 1');

console.log(foundValue);