如果 choices
数组中的任何 choice
对象在任何 results
数组中都找不到,则隐藏 choice
本例中的元素 {"choice": "f"}
和 {"choice": "g"}
在这 3 个结果中都不可用,所以我需要隐藏它。我该怎么做?
{"choices":[
{"choice": "a"},
{"choice": "b"},
{"choice": "c"},
{"choice": "d"},
{"choice": "e"},
{"choice": "f"},
{"choice": "g"}
],
"results":[
{"result":["a", "b", "c"]},
{"result":["a", "b", "d"]},
{"result":["a", "b", "e"]},
最佳答案
您可以从结果和过滤器选项中收集所有值。
var object = { choices: [{ choice: "a" }, { choice: "b" }, { choice: "c" }, { choice: "d" }, { choice: "e" }, { choice: "f" }, { choice: "g" }], results: [{ result: ["a", "b", "c"] }, { result: ["a", "b", "d"] }, { result: ["a", "b", "e"] }] },
hash = Object.create(null),
notIn = [];
object.results.forEach(function (a) {
a.result.forEach(function (b) {
hash[b] = true;
});
});
notIn = object.choices.filter(function (a) {
return !hash[a.choice];
});
console.log(notIn);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 与 Set
var object = { choices: [{ choice: "a" }, { choice: "b" }, { choice: "c" }, { choice: "d" }, { choice: "e" }, { choice: "f" }, { choice: "g" }], results: [{ result: ["a", "b", "c"] }, { result: ["a", "b", "d"] }, { result: ["a", "b", "e"] }] },
results = object.results.reduce((s, a) => new Set([...s, ...a.result]), new Set),
notIn = object.choices.filter(a => !results.has(a.choice));
console.log(notIn);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何比较一个数组中的元素到另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42651740/