Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 461
user3622460 Avatar asked Jan 30 '23 07:01

user3622460


1 Answers

EVEN SIMPLER

You could use the some operator. (It works by iterating over the array, when you return true it breaks out of the loop)

data.some(function(obj){
   if (obj.title ==== 'some value'){
        //change the value here
        obj.menu = 'new menu';
        obj.title = 'new title';
        return true;    //breaks out of he loop
   }
});
like image 65
Manish Poduval Avatar answered Feb 01 '23 00:02

Manish Poduval