我正在使用以下代码来查询API,它可以很好地返回JSON中的嵌套值:
const obj = response.data.map(function(item) {
return [item.id, item.jobNumber];
});
示例JSON:
{
"data": [
{
"id": 100,
"jobNumber": 1,
"jobTasks": [
{
"id": 12,
"cost": {
"amountString": 100
},
{
"id": 13,
"cost": {
"amountString": 500
}
}
}
]
},
{
"id": 101,
"jobNumber": 2,
"jobTasks": [
{
"id": 14,
"cost": {
"amountString": 100
},
{
"id": 15,
"cost": {
"amountString": 200
}
}
}]
}]
}
我现在想要遍历嵌套的作业任务,并为每个作业补充 item.jobTasks.cost.amountString ,以便可以返回以下内容:
答案 0 :(得分:2)
您可以使用Array#map()
创建新数组,Array#reduce()
汇总amountString
const apiJson = {"data":[{"id":100,"jobNumber":1,"jobTasks":[{"id":12,"cost":{"amountString":100}},{"id":13,"cost":{"amountString":500}}]},{"id":101,"jobNumber":2,"jobTasks":[{"id":14,"cost":{"amountString":100}},{"id":15,"cost":{"amountString":200}}]}]};
const output = apiJson.data.map(d=>({
jobNumber : d.jobNumber,
tasksCost : d.jobTasks.reduce((a,b)=>a.cost.amountString+b.cost.amountString)
}));
console.log(output);

答案 1 :(得分:2)
您可以使用接受reduce
方法的callback
方法。
此外,使用forEach
方法迭代data
个项目。
var json={
"data": [
{
"id": 100,
"jobNumber": 1,
"jobTasks": [
{
"id": 12,
"cost": {
"amountString": 100
}
},
{
"id": 13,
"cost": {
"amountString": 500
}
}
]
},
{
"id": 101,
"jobNumber": 2,
"jobTasks": [
{
"id": 14,
"cost": {
"amountString": 100
}
},
{
"id": 15,
"cost": {
"amountString": 200
}
}
]
}]
}
json.data.forEach(function(item){
var sum=item.jobTasks.reduce(function(sum,elem){
return sum+elem.cost.amountString;
},0);
console.log('jobNumber'+item.jobNumber+' '+sum);
});
答案 2 :(得分:1)
首先更新您的json,"}"在数组数据的第二个对象的jobTasks中缺少:
"jobTasks": [ { "id": 14,
"cost": {
"amountString": 100
}
},
{
"id": 15,
"cost": {
"amountString": 200
}
}
]
现在获得输出:
i = 0,1
item.jobTasks [I] cost.amountString;
答案 3 :(得分:0)
这是使用object-scan的解决方案。如今,我们在数据处理中经常使用它。请花一点时间将头缠住
const objectScan = require('object-scan');
const getCounts = (data) => objectScan(['data[*].jobTasks[*].cost.amountString'], {
filterFn: ({ parents, value, context }) => {
const jobNumber = parents[3].jobNumber;
context[jobNumber] = (context[jobNumber] || 0) + value;
}
})(data, {});
const apiJson = {"data":[{"id":100,"jobNumber":1,"jobTasks":[{"id":12,"cost":{"amountString":100}},{"id":13,"cost":{"amountString":500}}]},{"id":101,"jobNumber":2,"jobTasks":[{"id":14,"cost":{"amountString":100}},{"id":15,"cost":{"amountString":200}}]}]};
console.log(getCounts(apiJson));
// => { '1': 600, '2': 300 }