我想知道如何在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)
预期输出
{
"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"}
}
list
之前就将其传递给了nestedobj()
,因此它未被定义。 - Chayim Friedman