简体   繁体   English

使用循环创建动态嵌套对象

[英]Create Dynamically Nested Objects with loops

I wanna create a nested object dynamically.我想动态创建一个嵌套的 object。 I can create it hard coded.我可以创建硬编码。 Is it possible to do this with a loop?是否可以用循环来做到这一点?

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"

I want to pass an integer for example if it is "3", this should created an object like:我想传递一个 integer,例如如果它是“3”,这应该创建一个 object,例如:

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

If it is 4, :如果是 4,:

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

So on...很快...

edit:编辑:

I am also checking result object, in order to create this nested structure.我还在检查结果 object,以创建此嵌套结构。 If there is not any field yet, I simply create the object.如果还没有任何字段,我只需创建 object。

Using this structure to group data.使用此结构对数据进行分组。 Any chance to check these dynamically?有机会动态检查这些吗?

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

You can use reduceRight() for this. 您可以reduceRight()使用reduceRight() It just starts from the inside at the last item in the keys list and works its way out starting with "cool": 它只是从内部在键列表的最后一项开始,然后以“ cool”开始进行解决:

 let keys = ["a", "b", "c", "d"] let limit = 3 let result = keys.reduceRight((obj, key) => ({[key]: obj}), "cool") console.log(result) 

To limit where the object stops you can iterate over a slice of the keys. 要限制对象停止的位置,您可以遍历键的一部分。 For example: 例如:

 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) 

simple for-loop solution. 简单的for循环解决方案。

 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) 

If you like to add to a given object a new property, you could reduce the keys with the object and take default objects for not given keys. 如果要向给定对象添加新属性,则可以使用该对象减少键,并为未给定键使用默认对象。 At the end assign the value. 最后分配值。

 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; } 

I'd use a reducer, along with some basic tests to help me out: https://youtu.be/D6zLI8zrfVs 我会使用减速器以及一些基本测试来帮助我: https : //youtu.be/D6zLI8zrfVs

在此处输入图片说明

https://gist.github.com/brianswisher/2ce1ffe3ec08634f78aacd1b7baa31f9 https://gist.github.com/brianswisher/2ce1ffe3ec08634f78aacd1b7baa31f9

short and simple using reduce使用 reduce 简短而简单

let object1= {}
keys = ['a', 'b', 'c']

keys.reduce((prev,curr,i)=>{
    prev[curr] = {}
    return prev[curr]
}, object1)

log(object1) 
// {
//   a:{
//     b:{
//        c:{}
//     }
//   }
// }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM