Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

JavaScript: Change All Values of Deeply nested object given path

I have a JavaScript Object like this:

const Obj = {
  level1_1: "Value1",
  level1_2: "Value2",
  level1_3: "Value3",
  level1_4: "Value4",
  level1_5: {
    level2_1: {
      level3_1: { level4_1:1, level4_2:2, level4_3:3, level4_4:4 },
      level3_2: { level4_a:1, level4_b:2, level4_c:3, level4_d:4 } 
    },
    level2_2: {
      level3_1: { level4_5:1, level4_6:2, level4_7:3, level4_8:4 },
      level3_2: { level4_e:1, level4_f:2, level4_g:3, level4_h:4 } 
    }
  }
};

I want to change the values of all the keys inside level1_5.level2_1.Level3_1 object (ie. all level4) dynamically but not other values.

question from:https://stackoverflow.com/questions/65909406/javascript-change-all-values-of-deeply-nested-object-given-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can iterate over the object attributes recursively while keeping track of the remaining path properties, if reached the last one and it exists, you can then change all the values:

const Obj = {
  level1_1: "Value1",
  level1_2: "Value2",
  level1_3: "Value3",
  level1_4: "Value4",
  level1_5: {
    level2_1: {
      level3_1: { level4_1:1, level4_2:2, level4_3:3, level4_4:4 },
      level3_2: { level4_a:1, level4_b:2, level4_c:3, level4_d:4 } 
    },
    level2_2: {
      level3_1: { level4_5:1, level4_6:2, level4_7:3, level4_8:4 },
      level3_2: { level4_e:1, level4_f:2, level4_g:3, level4_h:4 } 
    }
  }
};

function getUpdatedObject (obj = {}, path = [], newVal) {
  const targetLevel = path.length;
  return (function setValuesOfPath (obj, path, newVal, currentLevel = 1) {
    if(currentLevel === targetLevel && path.length === 1) {
      const target = obj[path[0]];
      if(target) Object.keys(target).forEach(key => target[key] = newVal);
    }
    for (var property in obj) {
      if (obj.hasOwnProperty(property)) {
        if (typeof obj[property] === "object") {
          if(property === path[0]) path.shift();
          setValuesOfPath(obj[property], path, newVal, currentLevel+1);
        }
      }
    }
    return obj
  }(obj, path, newVal));
}

console.log(getUpdatedObject(Obj, ["level1_5", "level2_1", "level3_1"], "a"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...