Arlen Beiler Arlen Beiler - 6 months ago 9
Javascript Question

Find a value in an array of objects in Javascript

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.

Answer

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