簡體   English   中英

如何使用 lodash 中的 includes 方法檢查對象是否在集合中?

[英]How do I use the includes method in lodash to check if an object is in the collection?

lodash 讓我檢查基本數據類型的成員資格, includes

_.includes([1, 2, 3], 2)
> true

但以下不起作用:

_.includes([{"a": 1}, {"b": 2}], {"b": 2})
> false

這讓我感到困惑,因為以下搜索集合的方法似乎做得很好:

_.where([{"a": 1}, {"b": 2}], {"b": 2})
> {"b": 2}
_.find([{"a": 1}, {"b": 2}], {"b": 2})
> {"b": 2}

我究竟做錯了什么? 如何使用includes檢查集合中對象的成員資格?

編輯:問題最初針對 lodash 2.4.1 版,已針​​對 lodash 4.0.0 更新

includes (以前稱為containsinclude )方法通過引用(或更准確地說,使用=== )比較對象。 因為您的示例中{"b": 2}的兩個對象文字代表不同的實例,所以它們不相等。 注意:

({"b": 2} === {"b": 2})
> false

但是,這會起作用,因為只有一個{"b": 2}實例:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

另一方面, where (v4 中已棄用)和find方法通過對象的屬性比較對象,因此它們不需要引用相等。 作為includes的替代方案,您可能想嘗試some (也別名為any ):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

通過pswg補充答案,這里是使用lodash 4.17.5實現此lodash其他三種方法,而不使用_.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

您可以使用find來解決您的問題

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM