簡體   English   中英

如何在 javascript 中將數組 object 更改為嵌套的 object

[英]How to change array object to nested object in javascript

我想知道如何將數組 object 更改為 javascript 中的嵌套 object。 list了數組 object,如何轉換為嵌套的 object

 function nestedobj(arrlist){ var result ={}; result.list1 = arrlist[0]; result.list2 = arrlist[1] return list; } var list= [ {id: 1, cn: "SG"}, {id: 2, cn: "TH"} ] var list1= [ {id: 1, cn: "SG"}, {id: 2, cn: "TH"}, {id: 3, cn: "MY"} ] var listobj = this.nestedobj(list); var listobj1 = this.nestedobj(list1); console.log(listobj) console.log(listobj1)

預計 Output

{
  "list1":{"id": 1, "cn": "SG"},
  "list2":{"id": 2, "cn": "TH"}
}

{
  "list1":{"id": 1, "cn": "SG"},
  "list2":{"id": 2, "cn": "TH"},
  "list3":{"id": 3, "cn": "MY"}
}

您可以使用Array#reduce方法(或簡單循環)生成 object ,其中id屬性或索引可用於生成屬性名稱。

 var list = [{id: 1, cn: "SG" }, { id: 2, cn: "TH" }] var list1 = [{ id: 1, cn: "SG" }, { id: 2, cn: "TH" }, { id: 3, cn: "MY" }] function convert(arr) { // iterate over the array return arr.reduce((obj, o, i) => { // define the property obj[`list${o.id}`] = o; // or with index obj[`list${i + 1}`] = o; // return object reference for next call return obj; // set initial value as empty object to keep the result }, {}) } // or with simple loop function convert1(arr) { const result = {}; for (let o of arr) result[`list${o.id}`] = o; return result } console.log(convert(list)); console.log(convert(list1)); console.log(convert1(list)); console.log(convert1(list1));

// 循環收集:

 var list = [ { id: 1, cn: "SG" }, { id: 2, cn: "TH" } ]; var list1 = [ { id: 1, cn: "SG" }, { id: 2, cn: "TH" }, { id: 3, cn: "MY" } ]; function nestedobj2(list) { let result = {}; for (const v of list) { result["list" + v.id] = v; } return result; } var listobj = nestedobj2(list); console.log("%j", listobj); listobj = nestedobj2(list1); console.log("%j", listobj); function nestedobj(list) { return list.reduce((x, data) => { x["list" + data.id] = data; return x; }, {}); } listobj = nestedobj(list); console.log("%j", listobj) listobj = nestedobj(list1); console.log("%j", listobj)
 .as-console-row {color: blue!important}

如果list后面的數字是項目的序數 position 加一

 var nestedobj = a => Object.fromEntries(Object.entries(a).map(([k, v]) => [`list${+k+1}`, v])); var list= [ {id: 1, cn: "SG"}, {id: 2, cn: "TH"} ] var list1= [ {id: 1, cn: "SG"}, {id: 2, cn: "TH"}, {id: 3, cn: "MY"} ] var listobj = nestedobj(list); var listobj1 = nestedobj(list1); console.log(listobj) console.log(listobj1)

但是,如果列表后面的數字與 object 的 id 相關

 var nestedobj = a => Object.fromEntries(Object.values(a).map(v => [`list${v.id}`, v])); var list= [ {id: 1, cn: "SG"}, {id: 2, cn: "TH"} ] var list1= [ {id: 1, cn: "SG"}, {id: 2, cn: "TH"}, {id: 3, cn: "MY"} ] var listobj = nestedobj(list); var listobj1 = nestedobj(list1); console.log(listobj) console.log(listobj1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM