Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 625
Arlen Beiler Avatar asked Sep 17 '12 15:09

Arlen Beiler


People also ask

How do you get a list of duplicate objects in an array of objects with JavaScript?

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.

How do you check if there are duplicates in an array JavaScript?

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.


2 Answers

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);
like image 69
Šime Vidas Avatar answered Oct 15 '22 01:10

Šime Vidas


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); 
like image 44
Asciiom Avatar answered Oct 15 '22 00:10

Asciiom