Replace all the nested object properties to particular value

Viewed 25

Write a function that should take an array of objects and it should replace a particular value of the key?

for example: in below object, all the value of "bar" should be replaced to "foo-bar"

let obj = {
  a: "foo",
  b: "bar",
  c: {
    d: "foo",
    e: "bar",
    f: {
      g: "test",
      h: "bar",
    }
  }
}

Note: All the nested object properties also needs to be replaced

1 Answers

Recursively loop through all the keys.

const obj = {
  a: 'foo',
  b: 'bar',
  c: {
    d: 'foo',
    e: 'bar',
    f: {
      g: 'test',
      h: 'bar',
    },
  },
};

function replaceValuesInObj(o, targetValue, replaceValue) {
  Object.keys(o).forEach((key) => { // forEach key in the object
    if (o[key] === targetValue) o[key] = replaceValue; // is the value your condition? set it to 'foo-bar'
    if (typeof o[key] === 'object' && o[key] !== null) { // if the key is an object (call the function recursively)
      replaceValuesInObj(o[key], targetValue, replaceValue);
    }
  });
}

replaceValuesInObj(obj, 'bar', 'foo-bar');
console.log(obj);

Related