是否可以使用 javascript "Set"对象来查找具有特定键的元素?
像这样的东西:
let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
let mySet = new Set(myObjects);
console.log(mySet.has({"name":"a"}));
最佳答案
不是这样,它会寻找你传入的特定对象,它不在集合中。
如果您的起点是对象数组,则不需要 Set
根本就只是Array.prototype.find
:
let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
let found = myObjects.find(e => e.name === "a");
console.log(found);
如果您已经有
Set
并且想要搜索匹配项,您可以直接通过 for-of
使用它的迭代器:let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
let mySet = new Set(myObjects);
let found = undefined; // the `= undefined` is just for emphasis; that's the default value it would have without an initializer
for (const e of mySet) {
if (e.name === "a") {
found = e;
break;
}
}
console.log(found);
...或间接通过
Array.from
(重新)创建(该)一个数组,然后使用 find
:let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
let mySet = new Set(myObjects);
let found = Array.from(mySet).find(e => e.name === "a");
console.log(found);
如果这是你需要经常做的事情,你可以给自己一个实用函数:
const setFind = (set, cb) => {
for (const e of set) {
if (cb(e)) {
return e;
}
}
return undefined; // undefined` just for emphasis, `return;`
// would do effectively th same thing, as
// indeed would just not having a `return`
// at at all
}
let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];
let mySet = new Set(myObjects);
let found = setFind(mySet, e => e.name === "a");
console.log(found);
你甚至可以把它放在
Set.prototype
(确保它是不可枚举的),但要注意与 future 添加到 Set
的内容发生冲突(例如,如果 Set.prototype
在某些时候得到了 find
方法,我一点也不感到惊讶)。
关于Javascript 在集合中搜索对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45389073/