miy*_*avv 4 javascript arrays object
我想知道如何在 javascript 中将数组对象更改为嵌套对象。我有list数组对象,如何转换为嵌套对象
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)Run Code Online (Sandbox Code Playgroud)
预期产出
{
"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"}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Array#reduce方法(或简单循环)生成对象,其中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));Run Code Online (Sandbox Code Playgroud)