javascriptarraysarray-of-dict

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.


Solution

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

    function search(nameKey, myArray){
        for (let i=0; i < myArray.length; i++) {
            if (myArray[i].name === nameKey) {
                return myArray[i];
            }
        }
    }
    
    const array = [
        { name:"string 1", value:"this", other: "that" },
        { name:"string 2", value:"this", other: "that" }
    ];
    
    const resultObject = search("string 1", array);
    console.log(resultObject)