Javascript搜索集合中的对象键

Ale*_*ges 2 javascript search key set

是否可以使用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"}));
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

不是这样,那将寻找你传入的特定对象,而不是在集合中.

如果您的起点是一个对象数组,则根本不需要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);
Run Code Online (Sandbox Code Playgroud)

如果您已经拥有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);
Run Code Online (Sandbox Code Playgroud)

...或间接通过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);
Run Code Online (Sandbox Code Playgroud)


如果这是你需要经常做的事情,你可能会给自己一个实用功能:

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);
Run Code Online (Sandbox Code Playgroud)

你甚至可以把那Set.prototype(确保它是不可枚举),但未来增加的相互冲突的提防Set(例如,我就不会在所有如果惊讶Set.prototype有一个find在某一点法).


Jon*_*lms 5

您可能只需要一组名称:

 let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];

let map = new Set(myObjects.map(el=>el.name));
console.log(map.has("a"));
Run Code Online (Sandbox Code Playgroud)

如果你想通过名字得到一个对象,那就是Map的用途:

let myObjects = [{"name":"a", "value":0}, {"name":"b", "value":1},{"name":"c", "value":2}];

let map = new Map(myObjects.map(el=>[el.name,el]));
console.log(map.get("a"));
Run Code Online (Sandbox Code Playgroud)