补充答案,以下是实现此用法的其他三种方法,而无需使用:p.s.w.g
lodash
4.17.5
_.includes()
假设你想将一个对象添加到对象数组中,只有当不存在时。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}]
如果要在第一种情况下返回 ,则可以检查返回的索引:Boolean
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true