1

I have an array of objects from a json like this

{  
   "images":[  
      {  
         "childFolder":[  
            {  
               "name":"Trước",
               "_id":"5ccbc1e4af2be32acd1da1dd"
            },
            {  
               "name":"Sau",
               "_id":"5ccbc1e4af2be32acd1da1dc"
            },
            {  
               "name":"X-Quang",
               "_id":"5ccbc1e4af2be32acd1da1db"
            }
         ]
      }
   ]
}

I want to add a field test with value yes like so

"test": "yes"

To an object with "name" = "Sau" using javascript

How can i do this? Any help would be appreciated :)

2
  • What is expected output? Commented May 3, 2019 at 4:34
  • expected output would be {"name":"Sau", "_id":"5ccbc1e4af2be32acd1da1dc","test":"yes"} and other object still the same Commented May 3, 2019 at 4:35

2 Answers 2

2

You can use Array.forEach to iterate over the array and then check for name "Sau" and update the object.

let obj = {"images":[{"childFolder":[{"name":"Trước","_id":"5ccbc1e4af2be32acd1da1dd"},{"name":"Sau","_id":"5ccbc1e4af2be32acd1da1dc"},{"name":"X-Quang","_id":"5ccbc1e4af2be32acd1da1db"}]}]};

obj.images.forEach(img => img.childFolder.forEach(v => {
  if(v.name === "Sau") v.test = "yes";
}));

console.log(obj);

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to loop an entire array, use find() instead. It will give you a better performance.

const obj = yourObject

obj.images
   .find(image => image.childFolder)
   .childFolder
   .find(person => person.name == 'Sau')
   .test = "yes"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.