【发布时间】:2019-10-22 17:38:56
【问题描述】:
在我的 JSON.parse 之后我有这个数据
data = [
{
"serviceType": "service1",
"method": "close",
"quantity": 56
},
{
"serviceType": "service1",
"method": "divert",
"quantity": 175
},
{
"serviceType": "service1",
"method": "reverted",
"quantity": 80
},
{
"serviceType": "service2",
"method": "close",
"quantity": 15
},
{
"serviceType": "service2",
"method": "divert",
"quantity": 149
},
{
"serviceType": "service2",
"method": "reverted",
"quantity": 149
},
{
"serviceType": "service3",
"method": "close",
"quantity": 87
},....
}
]
我需要它像 data.json 来自这个 d3 example 其中 categorie 是我的 serviceType,它是每个对象的第一个属性(每个 serviceType 一个对象),然后是每个对象的第二个属性应该是带有方法和数量的对象数组。
我一直在为data 中的每个对象使用forEach,并且我正在推动每个serviceType OK(没有第二个属性)中的第一个。问题是我不知道如何update对象values(第二个属性)在正确的对象内(根据当前的serviceType)。
finalArray = [];
data.forEach(function (d, index) {
var serviceType = d.serviceType;
const found = finalArray.some( el => el.serviceType === serviceType);
if (!found) {
var obj = createObj(d); //function returning an obj with the desired structure
finalArray.push(obj);
}...
});
这是转换应该如何结束的示例。
[
{
"serviceType": "service1",
"values": [
{
"quantity": 0,
"method": "close"
},
{
"quantity": 4,
"method": "divert"
},
{
"quantity": 12,
"method": "reverted"
},
{
"quantity": 0,
"method": "checked"
}
]
},
{
"serviceType": "service2",
"values": [
{
"quantity": 1,
"method": "close"
},
{
"quantity": 21,
"method": "divert"
},
{
"quantity": 13,
"method": "reverted"
},
{
"quantity": 6,
"method": "checked"
}
]
}, ...
【问题讨论】:
-
你有想要的结果的例子吗?
-
@NinaScholz 我编辑了问题,谢谢。
标签: javascript json