创建带有循环的动态嵌套对象

时间:2019-07-10 15:58:19

标签: javascript loops object

我想动态创建一个嵌套对象。我可以创建它的硬编码。是否可以通过循环执行此操作?

result = {}
keys = ["a", "b", "c", "d"]

result[keys[0]] = {}
result[keys[0]][keys[1]] = {}
result[keys[0]][keys[1]][keys[2]] = {}
result[keys[0]][keys[1]][keys[2]][keys[3]] = "cool"

例如,我想传递一个整数,如果它是“ 3”,则应该创建一个像这样的对象:

result = {
  "a": {
     "b": {
        "c": "cool"
     }
   }
}

如果是4,:

result = {
  "a": {
     "b": {
        "c": {
           "d": "cool"
        }
     }
   }
}

等等...

编辑:

我也在检查结果对象,以创建此嵌套结构。如果还没有任何字段,我只创建对象。

使用此结构将数据分组。 有机会动态检查这些内容吗?

if (!result[keys[0]]) 
if (!result[keys[0]][keys[1]]) 
if (!result[keys[0]][keys[1]][keys[2]]) 

4 个答案:

答案 0 :(得分:5)

您可以使用reduceRight()。它只是从键列表中最后一项的内部开始,然后以“ cool”开始进行解决:

let keys = ["a", "b", "c", "d"]
let limit = 3

let result = keys.reduceRight((obj, key) => ({[key]: obj}), "cool")

console.log(result)

要限制对象停止的位置,可以在一部分键上进行迭代。例如:

let keys = ["a", "b", "c", "d"]
let start = 0
let stop = 3 // slices are don't inlcude the last item, so this will stop at index 2

let result = keys.slice(start, stop).reduceRight((obj, key) => ({
  [key]: obj
}), "cool")

console.log(result)

答案 1 :(得分:0)

简单的for-loop解决方案。

let result = {}
let keys = ["a", "b", "c", "d"]
let depth=3;

let current = result
for(let i=0;i<depth;++i){
  let key = keys[i]
  if(i == depth-1) current[key] = 'cool'
  else current = current[key] = {}

}

console.log(result)

答案 2 :(得分:0)

如果您想向给定对象添加一个新属性,则可以使用该对象减少键,并为未给定键使用默认对象。最后,指定值。

function setValue(object, path, value, limit) {
    var keys = path.slice(0, limit),
        last = keys.pop();

    keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
    return object;
}

var result = { foo: 42 },
    keys = ["a", "b", "c", "d"];

setValue(result, keys, 'cool');
console.log(result);

setValue(result, keys, 'cool', 3);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

相关问题