How can I update a json object inside of an array?

user3622460 picture user3622460 · Oct 31, 2017 · Viewed 10.7k times · Source

I have an array of objects and I want to update some of the content. I figured I could just map through the objects, find the match I was looking for and than update it.

data = data.map(obj => {
   return this.state.objToFind === obj.title;   
   }).map(obj, idx) => {
      console.log("found " + obj.title);     // reads found + undefined?
      obj.menu = this.state.menu;
      obj.title = this.state.title;
      obj.content = this.state.content;
 });

However, this is not working. I find the object but obj.anything is undefined. My console.log reads "Found undefined".

Answer

Karim picture Karim · Oct 31, 2017
data.map(obj => {
  return this.state.objToFind === obj.title;   
})

the first map will return an array of true and false, the second map will loop through these values and the console.log("found " + obj.title) will prints "found + undefined" consequently.

maybe you wanted something like this.

data = data.filter(obj => {
   return this.state.objToFind === obj.title;   
   }).map(obj, idx) => {
      console.log("found " + obj.title);
      obj.menu = this.state.menu;
      obj.title = this.state.title;
      obj.content = this.state.content;
      return obj;
 });