简体   繁体   English

如何使用数组中的嵌套对象创建 Object

[英]How to create Object with nested Objects from an Array

I have an array [1, 2, 3] and I want to transfer it to object with nested parent-child objects's series like this:我有一个数组[1, 2, 3] ,我想将它转移到 object ,嵌套父子对象的系列如下:

{ value: 1, rest: { value: 2, rest: { value: 3, rest: null } } 

If I have an array [1, 2, 3, 4] the result will be like this:如果我有一个数组[1, 2, 3, 4] ,结果将是这样的:

{ value: 1, rest: { value: 2, rest: { value: 3, rest: { value:4, rest:null } } 

The best effort of me is this snippet of code:我最大的努力是这段代码:

 const arrayToList = (array) => { let list = { value: null, rest: null }; for (let e of array) { array.indexOf(e) === 0 && (list.value = e); array.indexOf(e) >= 1 && (list.rest = { value: e }); } return list; }; console.log(arrayToList([1, 2, 3]));

You can use reduceRight like so:您可以像这样使用reduceRight

let obj = arr.reduceRight((rest, value) => ({ value, rest }), null);

It starts building the object from the inside out;它开始从内到外构建 object; it starts by creating the innermost object and then it uses that object as the rest property for the next outer object and so on until there are no more items in the array. it starts by creating the innermost object and then it uses that object as the rest property for the next outer object and so on until there are no more items in the array.

Demo:演示:

 let obj = [1, 2, 3, 4].reduceRight((rest, value) => ({ value, rest }), null); console.log(obj);

You can create such object by running below recursive function:您可以通过在递归 function 下面运行来创建这样的 object:

 let arr = [1, 2, 3, 4]; let transform = (arr, obj) => { if(arr.length === 0){ return obj; } else { let last = arr[arr.length - 1]; let newArr = arr.slice(0, arr.length - 1); return transform(newArr, { value: last, rest: obj || null }) } }; console.log(transform(arr));

Use a recursive function:使用递归 function:

 let array = [1, 2, 3]; function arrayToL(array) { let el = array.splice(0, 1)[0]; let rtn = { value: el } rtn.rest = (array.length > 0)? arrayToL(array): null; return rtn; } console.log(arrayToL(array));

I suggest another solution using the spread operator and reversing the array and start building object from the array end:我建议使用spread operator并反转数组并从数组末端开始构建 object 的另一种解决方案:

 let arr = [1, 2, 4, 5] let obj = {} //object to be built arr.slice().reverse().forEach(item => { //i used the slice method //in order to avoid mutating //the original variable obj = {...obj, ...{ value: item, rest: obj } }; }) console.log(obj)

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

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