我有这个JSON:
{
"my_obj": [
{
"qte": [
{
"qte1": "2",
"somthing": "toto"
},
{
"qte1": "1",
"somthing": "tata"
}
]
},
{
"qte": [
{
"qte1": "77"
},
{
"somthing": "titi"
}
]
}
]
}
我需要使用递归或一些函数nodeJs添加所有键“qte1”,这样做得到类似的东西:
{
"sumQte" : 80
}
祝你好运
答案 0 :(得分:1)
有很多方法可以解决你的这个问题。这可能不是最佳的..
const test = {
"my_obj": [
{
"qte": [
{
"qte1": "2",
"somthing": "toto"
},
{
"qte1": "1",
"somthing": "tata"
}
]
},
{
"qte": [
{
"qte1": "77"
},
{
"somthing": "titi"
}
]
}
]
};
let sum = 0;
test.my_obj.map(obj => {
obj.qte.map(obj2 =>{
if(obj2.qte1 != null){
sum+=parseInt(obj2.qte1);
}
});
});
console.log(sum);
答案 1 :(得分:1)
.product {
position:relative;
width:300px;
height:200px;
overflow-x:hidden;
overflow-y:visible;
}
答案 2 :(得分:1)
您可以使用迭代和递归方法进行一些检查,或者如果找到密钥或者实际数据是对象 - 那么再次调用该函数。
适用于任何深度。
function getSum(object, key) {
return Object.keys(object).reduce(function (s, k) {
if (!object[k]) {
return s;
}
if (k === key) {
return s + +object[k];
}
if (typeof object[k] === 'object') {
return s + getSum(object[k], key);
}
return s;
}, 0);
};
var data = { my_obj: [{ qte: [{ qte1: "2", somthing: "toto" }, { qte1: "1", somthing: "tata" }] }, { qte: [{ qte1: "77" }, { somthing: "titi" }] }] },
sum = getSum(data, 'qte1');
console.log(sum);