我需要在数组JSON中使用NodeJS进行添加,然后像这样返回更改的JSON,我还需要检查密钥是否存在以避免异常:
JSON:
{
"cmd": [
{
"sales": [
{
"qte1": "2",
"qte2": "3",
"someString": "test
},
{
"qte1": "66",
"someAttribute": "test "
},
{
"qte2": "77",
"toto": "tata"
}
]
}
]
}
目标JSON:
{
"cmd": [
{
"sales": [
{
"qte1": "2",
"qte2": "3",
"somme": "5"
},
{
"qte1": "66",
"somme": "66"
},
{
"qte2": "77",
"somme": "77"
}
]
}
]
}
我需要添加两个键qte1 et qte2 你有什么建议吗?
祝你好运
答案 0 :(得分:3)
似乎你只想要现有密钥的总和,使用几个.map
命令和一个.reduce
应该非常简单:
return json.cmd.map(function(salesList) {
return salesList.sales.map(function(sale) {
var keysToAdd = ["qte1", "qte2"];
sale.somme = Object.keys(sale).reduce(function(total, key) {
return total += keysToAdd.indexOf(key) > -1 ? +sale[key] : 0;
}, 0);
return sale;
});
});
答案 1 :(得分:1)
const data =
{
"cmd": [
{
"sales": [
{
"qte1": "2",
"qte2": "3"
},
{
"qte1": "66"
},
{
"qte2": "77"
}
]
}
]
};
function sum(dataObj) {
const hasCmd = dataObj && dataObj.cmd && dataObj.cmd.length > 0;
const hasSales = hasCmd && dataObj.cmd[0].sales && dataObj.cmd[0].sales.length > 0;
if (hasCmd && hasSales) {
const clonedArray = dataObj.cmd[0].sales.slice();
const summedArray = clonedArray.map(function(group) {
const groupKeys = Object.keys(group);
const sum = groupKeys.reduce(function (total, key) {
return total + parseInt(group[key], 10 /* Decimal Radix */);
}, 0);
return Object.assign({}, group, { 'somme': sum.toString() });
});
// build a new object to return to include new summed array
return { "cmd": [{ "sales": summedArray }] };
}
return dataObj;
}
console.log('data', JSON.stringify(data));
const newData = sum(data);
console.log('newData', JSON.stringify(newData));
答案 2 :(得分:0)
也许你可以先和你的树一样反射你的树。
就像那样:
{
command: [
{
sales: [
{
quantity: [1, 2, 4],
sum: 7
}
]
}
]
}

但是,尝试在行中使用正确类型的值,并尝试记住永远不要变异和对象,使用像map这样的仿函数并减少:
const cmd = [
{
sales: [
{
quantity: [1, 2, 3],
sum: 0
},
{
quantity: [67, 2, 3],
sum: 0
}
]
}
];
const newObjectWithSum = cmd.map(sales => {
return sales.sales.map((sale) => {
sale.sum = sale.quantity.reduce((valueIn, next) => {
return valueIn + next;
},0);
return sale;
});
})