从对象数组中过滤唯一值 [英] Filter unique values from an array of objects
本文介绍了从对象数组中过滤唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Array.filter()和name
返回唯一的id
?
How can I use Array.filter() to return unique id
with name
?
我的方案与我研究的解决方案稍有不同,因为我有一系列对象.我发现的每个示例都包含单个值的平面数组.
My scenario is slightly different than the solutions I have researched in that I have an array of objects. Every example I find contains a flat array of single values.
data=[
{id: 555, name: "Sales", person: "Jordan" },
{id: 555, name: "Sales", person: "Bob" },
{id: 555, name: "Sales", person: "John" },
{id: 777, name: "Accounts Payable", person: "Rhoda" },
{id: 777, name: "Accounts Payable", person: "Harry" },
{id: 888, name: "IT", person: "Joe" },
{id: 888, name: "IT", person: "Jake" },
];
var unique = data.filter(
function (x, i) {
return data[i].id.indexOf(x.id) === i
});
谢谢.
推荐答案
I think forEach()
is better to achieve what you are looking for:
var data=[
{id: 555, name: "Sales", person: "Jordan" },
{id: 555, name: "Sales", person: "Bob" },
{id: 555, name: "Sales", person: "John" },
{id: 777, name: "Accounts Payable", person: "Rhoda" },
{id: 777, name: "Accounts Payable", person: "Harry" },
{id: 888, name: "IT", person: "Joe" },
{id: 888, name: "IT", person: "Jake" },
];
var resArr = [];
data.forEach(function(item){
var i = resArr.findIndex(x => x.name == item.name);
if(i <= -1){
resArr.push({id: item.id, name: item.name});
}
});
console.log(resArr);
If you really want to use filter()
try the following way:
var data=[
{id: 555, name: "Sales", person: "Jordan" },
{id: 555, name: "Sales", person: "Bob" },
{id: 555, name: "Sales", person: "John" },
{id: 777, name: "Accounts Payable", person: "Rhoda" },
{id: 777, name: "Accounts Payable", person: "Harry" },
{id: 888, name: "IT", person: "Joe" },
{id: 888, name: "IT", person: "Jake" },
];
var resArr = [];
data.filter(function(item){
var i = resArr.findIndex(x => x.name == item.name);
if(i <= -1){
resArr.push({id: item.id, name: item.name});
}
return null;
});
console.log(resArr);
这篇关于从对象数组中过滤唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文