我有以下数组:
const HEROES = [
{ id: 1, name: 'Captain America', squad: 'Avengers' },
{ id: 2, name: 'Iron Man', squad: 'Avengers' },
{ id: 3, name: 'Spiderman', squad: 'Avengers' },
{ id: 4, name: 'Superman', squad: 'Justice League' },
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' },
{ id: 6, name: 'Aquaman', squad: 'Justice League' },
{ id: 7, name: 'Hulk', squad: 'Avengers' },
];
我正在尝试将另一个对象{id:5,小队:“正义联盟”}传递到数组中以找到匹配的对象。
例如:
findOne(HEROES, { id: 5, squad: 'Justice League' })
应该返回
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' }
我不确定如何启动此程序,将不胜感激。
答案 0 :(得分:3)
使用find
:
const HEROES = [
{ id: 1, name: 'Captain America', squad: 'Avengers' },
{ id: 2, name: 'Iron Man', squad: 'Avengers' },
{ id: 3, name: 'Spiderman', squad: 'Avengers' },
{ id: 4, name: 'Superman', squad: 'Justice League' },
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' },
{ id: 6, name: 'Aquaman', squad: 'Justice League' },
{ id: 7, name: 'Hulk', squad: 'Avengers' },
];
const findOne = (arr, query) => {
const { id, squad } = query;
return arr.find(({ id: a, squad: b }) => (id != undefined ? a == id : true) && (b != undefined ? b == squad : true));
};
console.log(findOne(HEROES, { id: 5, squad: "Justice League" }));
答案 1 :(得分:0)
看看下划线JS或Lodash之类的实用程序库。他们具有这种功能。
来自lodash文档:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];
_.find(users, function(o) { return o.age < 40; });
// => object for 'barney'
// The `_.matches` iteratee shorthand.
_.find(users, { 'age': 1, 'active': true });
// => object for 'pebbles'
答案 2 :(得分:0)
使用find
const HEROES = [
{ id: 1, name: 'Captain America', squad: 'Avengers' },
{ id: 2, name: 'Iron Man', squad: 'Avengers' },
{ id: 3, name: 'Spiderman', squad: 'Avengers' },
{ id: 4, name: 'Superman', squad: 'Justice League' },
{ id: 5, name: 'Wonder Woman', squad: 'Justice League' },
{ id: 6, name: 'Aquaman', squad: 'Justice League' },
{ id: 7, name: 'Hulk', squad: 'Avengers' },
];
const findOne=(arr,obj)=>arr.find(x=>x.id==obj.id&&x.squad==obj.squad);
console.log(findOne(HEROES, { id: 7, squad: 'Avengers' }));