0

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.

3 Answers 3

2

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)

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

Comments

1

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)

1 Comment

why map if the returned array is void?
0

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; }

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.