我有一个像这样的json对象。
每个json对象都可以有共同的Product
名称,例如orgs[0]
& orgs[3]
具有相同的产品名称。
"orgs":
[{
"Budget Actual Consumption": "12.00",
"Budget Planned Consumption": "50.00",
"Product": "Loyalty CO-brand"
}, {
"Budget Actual Consumption": "11.00",
"Budget Planned Consumption": "60.00",
"Product": "Loaylty Rebates"
}, {
"Budget Actual Consumption": "10.00",
"Budget Planned Consumption": "7.00",
"Product": "Loaylty Rebates"
}, {
"Budget Actual Consumption": "9.00",
"Budget Planned Consumption": "8.00",
"Product": "Loyalty CO-brand"
}]
是否可以创建一个新阵列,使其具有唯一的多个对象,每个对象都有唯一的产品名称&其他关键将总结
例如
var someArray = [{
name:"Loyalty CO-brand",
bac:"21" //12+9
pac:"58" //50+8
},{
name:"Loaylty Rebates",
bac:"21" //10+11
pac:"67" //60+7
}]
我首先尝试创建一个唯一的Product
数组,然后在另一个内部使用forEach
两次。但我无法成功完成,因为我不确定如果匹配Products
答案 0 :(得分:3)
假设结果应按Product
分组,您可以使用对象作为结果数组对象的哈希表。
如果省略获取字符串而不是数字的要求,则算法会更短。
var data = { "orgs": [{ "Budget Actual Consumption": "12.00 ", "Budget Planned Consumption": "50.00 ", "Product": "Loyalty CO-brand" }, { "Budget Actual Consumption": "11.00 ", "Budget Planned Consumption": "60.00 ", "Product": "Loaylty Rebates" }, { "Budget Actual Consumption": "10.00 ", "Budget Planned Consumption": "7.00 ", "Product": "Loaylty Rebates" }, { "Budget Actual Consumption": "9.00 ", "Budget Planned Consumption": "8.00 ", "Product": "Loyalty CO-brand" }] },
grouped = [];
data.orgs.forEach(function (a) {
if (!this[a.Product]) {
this[a.Product] = { name: a.Product, bac: '0', pac: '0' };
grouped.push(this[a.Product]);
}
this[a.Product].bac = (+this[a.Product].bac + +a['Budget Actual Consumption']).toString();
this[a.Product].pac = (+this[a.Product].bac + +a['Budget Planned Consumption']).toString();
}, Object.create(null));
console.log(grouped);
答案 1 :(得分:3)
使用var org = { "orgs": [{ "Budget Actual Consumption": "12.00 ", "Budget Planned Consumption": "50.00 ", "Product": "Loyalty CO-brand" }, { "Budget Actual Consumption": "11.00 ", "Budget Planned Consumption": "60.00 ", "Product": "Loaylty Rebates" }, { "Budget Actual Consumption": "10.00 ", "Budget Planned Consumption": "7.00 ", "Product": "Loaylty Rebates" }, { "Budget Actual Consumption": "9.00 ", "Budget Planned Consumption": "8.00 ", "Product": "Loyalty CO-brand" }] },
newArr = [], bac = 'Budget Actual Consumption', pac = 'Budget Planned Consumption';
org.orgs.forEach(function (o) {
if (!this[o.Product]) {
this[o.Product] = {name: o.Product, bac: +o[bac], pac: +o[pac]};
newArr.push(this[o.Product]);
} else {
this[o.Product]['bac'] += +o[bac];
this[o.Product]['pac'] += +o[pac];
}
}, {});
console.log(JSON.stringify(newArr, 0, 4));
函数的解决方案:
[
{
"name": "Loyalty CO-brand",
"bac": 21,
"pac": 58
},
{
"name": "Loaylty Rebates",
"bac": 21,
"pac": 67
}
]
输出:
{{1}}
答案 2 :(得分:2)
http://codepen.io/therealplato/pen/KMWPPN
//foo = {"orgs":[...]}
console.log(foo);
grouped = _.groupBy(foo.orgs, grouper);
console.log(grouped);
function grouper(item) {
return item["Product"];
}