js如何动态添加属性值?

新手上路,请多包涵
当nodeList长度为2的时候 obj= _tableArray[nodeList[0]].children[nodeList[1]] ;以此类推如何用循环去写  
let  editIndex = '0_1',let  editIndex = '0_1_1',let  editIndex = '0_1_1_2'
代码如下
let nodeList = editIndex.split('_')
let obj = {}
if(nodeList.length == 2){
   obj= _tableArray[nodeList[0]].children[nodeList[1]]                
}
if(nodeList.length == 3){
   obj= _tableArray[nodeList[0]].children[nodeList[1]].children[nodeList[2]]
 }
if(nodeList.length == 4){
   obj= _tableArray[nodeList[0]].children[nodeList[1]].children[nodeList[2]].children[nodeList[3]]
 }

预期结果:用循环去写,现在是写死的,当长度是2的时候是
obj= _tableArray[nodeList[0]].children[nodeList[1]]

阅读 596
avatarAI BotBETA

你可以使用递归来动态地构建这个对象路径。首先,你可以定义一个递归函数,该函数会接收当前的对象和路径的下一个索引作为参数。然后,它会检查是否还有更多的索引需要处理,如果有,就递归地调用自身,否则返回当前的对象。

下面是一个使用 JavaScript 实现的示例:

function getObj(obj, indices) {
  let current = obj;
  for (let i = 0; i < indices.length; i++) {
    current = current.children[indices[i]];
  }
  return current;
}

let editIndex = '0_1_1_2';
let nodeList = editIndex.split('_');
let _tableArray = {
  // 你的_tableArray数据
};

let obj = getObj(_tableArray, nodeList);

在这个示例中,getObj 函数会遍历 indices 数组中的每个索引,并使用这些索引从 obj 中获取子对象。当遍历完所有的索引后,它就会返回最终的对象。

请注意,这个示例假设 _tableArray 和其所有子对象都有 children 属性,并且 nodeList 中的每个索引都是有效的。如果这些假设不成立,你可能需要添加一些额外的错误检查和处理逻辑。

1 个回答
✓ 已被采纳
nodeList.reduce((p, c) => p.children[c], { children: _tableArray })

测试:

const _tableArray: any[] = [],
    nodeList = [0, 1, 2, 3]

nodeList.forEach((_, i) => (_tableArray[i] = { children: _tableArray, i }))

const o2 = _tableArray[nodeList[0]].children[nodeList[1]],
    o3 = _tableArray[nodeList[0]].children[nodeList[1]].children[nodeList[2]],
    o4 = _tableArray[nodeList[0]].children[nodeList[1]].children[nodeList[2]]
            .children[nodeList[3]],
    getN = (n: number) =>    nodeList
            .slice(0, n)
            .reduce((p, c) => p.children[c], { children: _tableArray, i: undefined })
            .i

console.assert(o2.i === getN(2), '2')
console.assert(o3.i === getN(3), '3')
console.assert(o4.i === getN(4), '4')