我想根据一个键过滤掉我的对象数组。如果该键在其他对象中相同,则将添加对象的第二个值。我有一个像下面这样的对象数组:
输入:
var myArray = [
{
_name : "Mike",
_amount : "7"
},
{
_name : "Julius",
_amount : "10"
},
{
_name : "Edison",
_amount : "2"
},
{
_name : "Mike",
_amount : "10"
},
{
_name : "Kate",
_amount : "0"
},{
_name : "Edison",
_amount : "10"
}
]
输出:
var myNewArray = [
{
_name : "Mike",
_amount : "17"
},
{
_name : "Julius",
_amount : "10"
},
{
_name : "Edison",
_amount : "12"
},
{
_name : "Kate",
_amount : "0"
},
]
迈克和爱迪生重复了两次,因此_amount键为这些对象添加了值。它对我来说有点困惑。请帮帮我。谢谢!
答案 0 :(得分:3)
您可以使用Array#forEach
和对象作为插入对象的参考。
var myArray = [{ _name: "Mike", _amount: "7" }, { _name: "Julius", _amount: "10" }, { _name: "Edison", _amount: "2" }, { _name: "Mike", _amount: "10" }, { _name: "Kate", _amount: "0" }, { _name: "Edison", _amount: "10" }],
newArray = [];
myArray.forEach(function (a) {
if (!this[a._name]) {
this[a._name] = { _name: a._name, _amount: 0 };
newArray.push(this[a._name]);
}
this[a._name]._amount = (+this[a._name]._amount + +a._amount).toString(); // if you really
}, Object.create(null)); // need strings
console.log(newArray);
按要求排序_amount
降序
var myArray = [{ _name: "Mike", _amount: "7" }, { _name: "Julius", _amount: "10" }, { _name: "Edison", _amount: "2" }, { _name: "Mike", _amount: "10" }, { _name: "Kate", _amount: "0" }, { _name: "Edison", _amount: "10" }],
newArray = [];
myArray.forEach(function (a) {
if (!this[a._name]) {
this[a._name] = { _name: a._name, _amount: 0 };
newArray.push(this[a._name]);
}
this[a._name]._amount += +a._amount
}, Object.create(null));
newArray.sort(function (a, b) {
return b._amount - a._amount;
});
console.log(newArray);
答案 1 :(得分:1)
就ES6而言,这就是它的完成方式。
var myArray = [
{
_name : "Mike",
_amount : "7"
},
{
_name : "Julius",
_amount : "10"
},
{
_name : "Edison",
_amount : "2"
},
{
_name : "Mike",
_amount : "10"
},
{
_name : "Kate",
_amount : "0"
},{
_name : "Edison",
_amount : "10"
}
],
result = myArray.reduce((p,c) => {var o = p.find(e => e._name == c._name);
!!o ? o._amount = (o._amount*1+c._amount*1)+"" : p.push(c);
return p;},[]).sort((a,b) => b._amount-a._amount);
console.log(result);

答案 2 :(得分:0)
您要使用的是存储密钥(名称)及其相应金额的地图。如果您再次遇到密钥,则可以为密钥添加相应的金额。然后,您可以浏览地图并将对象添加到数组中。
var myArray = [
{
_name:"Mike",
_amount: 7
},
{
_name:"Julius",
_amount: 10
},
{
_name:"Edison",
_amount: 2
},
{
_name:"Mike",
_amount: 10
},
{
_name:"Kate",
_amount: 0
},{
_name:"Edison",
_amount: 10
}
];
var map = {};
for (var i = 0 ; i < myArray.length ; i++) {
var key = myArray[i]['_name'];
var amount = myArray[i]['_amount'];
if (!map[key]) {
map[key] = amount;
} else {
map[key] += amount;
}
}
var outputArray = [];
for (var key in map) {
if (map.hasOwnProperty(key)) {
outputArray.push({_name: key, _amount: map[key]});
}
}