Souvik Ray
Souvik Ray

Reputation: 3018

How to update value for a certain key in a list of objects in Javascript?

I am new to Javascript. I have an object that looks like below

let final_json = {"ab": [{"cd": "ee", "col_val": {}},{"ef": "uu", "col_val": {"gg": "hh"}}]}

Now I want to update the col_val key's value with a defined value of my own. But I also need to ensure that the key cd exists in the given object.

This is what I do

if(final_json["ab"]) {    
    Object.entries(final_json["ab"]).forEach(([key, val]) => {
        if(final_json["ab"][key].hasOwnProperty("cd")) {
            // update the col_val value with {"rr": "ff"}
        }
    })
}

I am just not able to figure out how do I do that. Any help will be appreciated.

Upvotes: 0

Views: 796

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386540

You could find the wanted object and update the property, if found.

let object = { ab: [{ cd: "ee", col_val: {} }, { ef: "uu", col_val: { gg: "hh" } }] },
    target = (object["ab"] || []).find(o => 'cd' in o);

if (target) {
    target.col_val = { rr: "ff" };
}

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

holydragon
holydragon

Reputation: 6728

Here I use .forEach and just check for the cd property then update col_val.

let final_json = {"ab": [{"cd": "ee", "col_val": {}},{"ef": "uu", "col_val": {"gg": "hh"}}]}
final_json.ab.forEach(o => {
  if (o.cd) o.col_val = {testKey: "testValue"}
})
console.log(final_json)

Upvotes: 2

ellipsis
ellipsis

Reputation: 12152

Use map and check for cd using hasOwnProperty() function. hasOwnProperty() tells if a specific property is present in the object or not. Refer

let final_json = {
  "ab": [{
    "cd": "ee",
    "col_val": {}
  }, {
    "ef": "uu",
    "col_val": {
      "gg": "hh"
    }
  }]
};
final_json.ab.map(e => {
  if (e.hasOwnProperty('cd'))
      e.col_val = 'my value'
    return e;
})
console.log(final_json)

Upvotes: 1

Related Questions