我有一个二维数组datas[0]
,我想将其转换为一个对象数组。
密钥位于name
,我想提取它们,child
,size
和var test = new Object();
for (i = 0; i < datas.length; i++){
var obj = new Object();
obj.name = datas[i][0];
obj.parent = datas[i][1];
obj.size = datas[i][2];
test.update(obj);
}
。然后将每个属性附加到它以获取主对象。出于某种原因,它会覆盖并且在我尝试时只显示一个对象?
[
{"name": "Billy", "parent":"Ann", "size": "1"},
{"name": "Ben", "parent": "John", "size": "1"},
etc...
]
我希望最终结果是:
datas
[["Name", "Parent", "Size"], ["Billy", "Ann", "1"], ["Ben", "John", "1"] ... ]
数组如下所示:
{{1}}
答案 0 :(得分:0)
您无法创建没有属性的对象,因此无法实现您想要的结果。
假设你想要:
[
{"name": "Billy", "parent": "Ann", "size": "1"},
{"name": "Ben", "parent": "John", "size": "1"},
etc...
]
尝试:
var test = [];
for(i = 0; i < datas.length; i++){
test.push({
name: datas[i][0],
parent: datas[i][1],
size: datas[i][2]
});
}
// do something with test
答案 1 :(得分:0)
{
{"name": "Billy", "parent":"Ann", "size"="1"},
{"name": "Ben", "parent": "John", "size" = "1"}
}
是不正确的json。花括号意味着 - 对象,对象必须以key:value形式呈现。有两种可能的正确json:
对象数组
[
{"name": "Billy", "parent":"Ann", "size"="1"},
{"name": "Ben", "parent": "John", "size" = "1"}
]
深层结构
{
"Billy" {"parent":"Ann", "size"="1"},
"Ben" {"parent": "John", "size" = "1"}
}
生成第一个变体
var res = []
for(i = 0; i<datas.length; i++){
var obj = new Object();
obj.name = datas[i][0];
obj.parent = datas[i][1];
obj.size = datas[i][2];
res.push(obj);
}
JSON.stringify(res);
生成第二个变体
var res = new Object();
for(i = 0; i<datas.length; i++){
var obj = new Object();
obj.parent = datas[i][1];
obj.size = datas[i][2];
res.[datas[i][0]] = obj;
}
JSON.stringify(res);