javascript - 如何动态访问对象然后编辑其内容
问题描述
所以我有例如这样一个对象:
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[]
解决方案
您可以首先使用 获取索引数组中的最后一个索引.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);
推荐阅读
- ajax - Ajax 表单中的 Django Manytomanyfield
- php - Symfony 4.1:ArrayCollection 上的 UniqueEntity 验证
- c# - C# 使用 OleDb 读取导出的文件 Excel(总是得到异常外部表不是预期的格式)
- apache - Apache 错误日志可能有更多信息...
- scala - 如何将 ByteArrayInputStream 转换为文件或图像
- plsql - 更改命令以分区和子分区表 oracle 12c
- sql - 使用 Like 运算符创建内连接
- spring-boot - 在哪种情况下 kubernates pod 会停止工作?
- angular - 自定义 Ag-Grid 状态栏
- android - 反应原生模块:无法解决:com.google.android.exoplayer:exoplayer-core:2.7.3