朋友们,关于Creating JSON structure from JSON results的问题,我怎样才能创建具有多个数组头的对象?
Here is my Fiddle我的代码如下。
var array = [
[{
"label": "NewNetworkServiceProvider",
"value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "PurchaseOrderNumber",
"value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "RawRecordType",
"value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}],
[{
"label": "NewNetworkServiceProvider",
"value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "PurchaseOrderNumber",
"value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "RawRecordType",
"value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5m321"
}]
];
var obj = {
header: {}
};
array.forEach(function (item) {
item.forEach(function (data) {
obj.header[data.label] = data.value;
});
});
console.log(obj)
答案 0 :(得分:0)
猜测我认为你想要这个:
array.forEach(function (item) {
item.forEach(function (data) {
obj.header[data.label] = obj.header[data.label] || [];
obj.header[data.label].push(data.value);
});
});
答案 1 :(得分:0)
您的array
不正确。如果你有不同的标签名称,你提供的JS代码就可以完美地运行,如果标签名称相同,那么最新的值将取代旧值。
所以,试试这段代码吧。它给出了所有标题名称。
var array = [
[{
"label": "0_NewNetworkServiceProvider",
"value": "0_NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "0_PurchaseOrderNumber",
"value": "0_PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "0_RawRecordType",
"value": "0_RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}],
[{
"label": "1_NewNetworkServiceProvider",
"value": "1_NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "1_PurchaseOrderNumber",
"value": "1_PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "1_RawRecordType",
"value": "1_RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5m321"
}]
];
var obj = {
header: {}
};
array.forEach(function(item) {
item.forEach(function(data) {
obj.header[data.label] = data.value;
});
});
console.log(obj)
查看array
数据的差异。
@Jaromanda X也是正确的,但他在每个标题内取出记录为数组。