以下是使用lodash 4.17.5 实现此目的的三种方法:
假设您想将对象entry 添加到对象数组numbers 中,前提是entry 尚不存在。
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
/*
* 4. This will return `true` if the entry exists, false otherwise.
*/
_.some(numbers, entry);
// output: true
如果你想返回一个Boolean(即假设你没有使用_.some()),在第一种情况下,你可以简单地检查返回的索引值:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
Lodash documentation 是示例和实验的重要来源。