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.
To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
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);
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With