我有两个与ID相关的JS相关对象。我需要根据第二个对象值color
过滤第一个对象。 filter函数对我有用,但是我得到一个数组,我需要一个对象。
这些对象类似如下:
"matchs": {
"123": {
id: "123",
array_players: [ "1","2" ],
},
"345": {
id: "345",
array_players: [ "1","4" ],
},
"611": {
id: "611",
array_players: [ "2","5" ],
}
};
"players": {
"1": { "id": "1", "name": "Mike", color: "green"},
"2": { "id": "2", "name": "Andy", color: "yellow" },
"3": { "id": "3", "name": "Tony", color: "blue"},
"4": { "id": "4", "name": "Joe", color: "green" }
"5": { "id": "4", "name": "Lisa", color: "red" }
}
ES6过滤器功能:
var filter = Object.values(matchs).filter(function(match){
return (
match.array_players.find (function(player_id){
return (players[player_id].color === 'green')
})
);
});
但是结果是一个数组,而不是像原始
matchs
这样的对象:[
0: {
id: "123",
array_players: [ "1","2" ],
},
1: {
id: "345",
array_players: [ "1","4" ],
}
];
我需要这样的东西:
"matchs": {
"123": {
id: "123",
array_players: [ "1","2" ],
},
"345": {
id: "345",
array_players: [ "1","4" ],
},
};
最佳答案
您可以映射对象,并使用 Object.assign
将所有对象都放入一个对象中。
var matchs = { 123: { id: "123", array_players: ["1", "2"] }, 345: { id: "345", array_players: ["1", "4"] }, 611: { id: "611", array_players: ["2", "5"] } },
players = { 1: { id: "1", name: "Mike", color: "green" }, 2: { id: "2", name: "Andy", color: "yellow" }, 3: { id: "3", name: "Tony", color: "blue" }, 4: { id: "4", name: "Joe", color: "green" }, 5: { id: "4", name: "Lisa", color: "red" } },
result = Object.assign(
{},
...Object
.keys(matchs)
.filter(k => matchs[k].array_players.some(l => players[l].color === 'green'))
.map(k => ({ [k]: matchs[k] }))
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }