簡體   English   中英

如何使用數組中的嵌套對象創建 Object

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

我有一個數組[1, 2, 3] ,我想將它轉移到 object ,嵌套父子對象的系列如下:

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

如果我有一個數組[1, 2, 3, 4] ,結果將是這樣的:

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

我最大的努力是這段代碼:

 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]));

您可以像這樣使用reduceRight

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

它開始從內到外構建 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.

演示:

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

您可以通過在遞歸 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));

使用遞歸 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));

我建議使用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