Javascript 将数据分组到一个数组中,并从对象值数组中获取总和
我不熟悉react和javascript。这里我尝试使用lodsh函数 我有一个对象数组,看起来像Javascript 将数据分组到一个数组中,并从对象值数组中获取总和,javascript,lodash,Javascript,Lodash,我不熟悉react和javascript。这里我尝试使用lodsh函数 我有一个对象数组,看起来像 const data = [{ "Id": "1", "testone": 100, "test": 40, "Original": { "Id": "11"
const data = [{
"Id": "1",
"testone": 100,
"test": 40,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "INP"
}
}, {
"Id": "2",
"testone": 120,
"test": 20,
"Original": {
"Id": "10"
},
"__Parent__": {
"Id": "21",
"Status": "Book"
}
},{
"Id": "3",
"testone": 110,
"test": 140,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "INP"
}
}, {
"Id": "4",
"testone": 100,
"test": 40,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "Val"
}
}]
这里,我有一个函数,它有产品Id。我正在从另一个函数传递它=>
cont value = (PID, data) => {
}
那么这个函数,
我需要求和,首先我需要取所有Id与PID相同的对象。对象的Id应为原始.Id
。如果这些匹配之后,我需要检查对象的状态,比如,is status是INP还是BOOK
,那么求和需要取
testone key value or else need to take the `test` key value.
因此,在给定的示例中
100 + 100 + 40 which will be 240.
Id是11,传递给函数,在给定对象中,它匹配3个对象
现在,
当返回总和时,它会像
100 + 100 + 40 which will be 240.
那么,我该怎么做呢。谢谢。如果您支持IE9及其后版本,我认为最好使用
const sum = data.reduce((total, item) => {
if (item.Original.Id !== PID) return total;
const { status, testone, test } = item;
let addition = 0;
if (status === "INP") addition = testone;
else if (status === "BOOK") addition = test;
return total + addition;
}, 0);
我认为,如果您支持IE9及其后,最好使用它
const sum = data.reduce((total, item) => {
if (item.Original.Id !== PID) return total;
const { status, testone, test } = item;
let addition = 0;
if (status === "INP") addition = testone;
else if (status === "BOOK") addition = test;
return total + addition;
}, 0);
您可以使用data.filter(item)=>item.Original.Id==PID
获取具有匹配PID的项数组。然后,您可以在生成的数组上使用map
函数来执行求和逻辑。您可以使用data.filter(item)=>item.Original.Id==PID
来获取具有匹配PID的项目数组。然后,您可以在生成的数组上使用map
函数来执行求和逻辑。