首页 > 解决方案 > 如何动态访问对象然后编辑其内容

问题描述

所以我有例如这样一个对象:

let htmlDom = [
  {
    type: "div",
    att: {
      class: ["test", "test2"],
      id: "yoyo",
      "data-hello": ["jan", "john"],
    },
    content: "Hello",
    child: [
      {
        type: "div",
        content: "test",
        child: [{}],
      },
    ],
  },
];

现在我想动态访问它,例如:htmlDom[0].child[0].child[0],现在孩子的数量可以变化,而且数量一般。例如,我有一个 [0, 0, 0] 数组,然后我如何使用数组中的数字动态访问该路径,然后更改最后一个子项 [0] 的内容?问题是,例如数组稍后可以更改为 [0,2,4,3,6] 等,并且取决于数组长度,我需要创建更多 .child[]

标签: javascriptarraysjsonalgorithmobject

解决方案


您可以首先使用 获取索引数组中的最后一个索引.pop(),然后.reduce()在现在修改的索引数组上使用来迭代您的子数组。通过将累加器设置为起始htmlDom,您可以访问每个索引处的对象及其每次迭代的子数组.reduce(),其中child返回每个对象的数组。然后将此子数组用作acc您的 reduce 方法的下一次调用/迭代。找到最后一个子数组后,您可以使用之前从数组中弹出的索引来设置/更新值:

let htmlDom = [ { type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [ { type: "div", content: "test", child: [{}], }, ], }, ];

const changeByIdxs = (arr, [...idxs], value) => {
  const lastIdx = idxs.pop();
  const finalArr = idxs.reduce((acc, i) => acc[i].child, arr);
  finalArr[lastIdx] = value;
}

changeByIdxs(htmlDom, [0, 0, 0], {x: 1});
console.log(htmlDom);

如果您发现上面的内容更容易理解,则可以使用 for 循环来实现:

const htmlDom = [{ type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [{ type: "div", content: "test", child: [{}], }, ], }, ];
const changeByIdxs = (arr, [...idxs], value) => {
  const lastIdx = idxs.pop();
  let finalArr = arr;
  for (let i = 0; i < idxs.length; i++) {
    const idx = idxs[i];
    finalArr = finalArr[idx].child;
  }
  finalArr[lastIdx] = value
}

changeByIdxs(htmlDom, [0, 0, 0], {x: 1});
console.log(htmlDom);


推荐阅读