3 回答
TA贡献1893条经验 获得超10个赞
最简单的答案是some:
let a = 'abc'
let b = [{title:'ccc'},{title:'abc'},{title:'ddd'}];
let aInB = b.some(({ title }) => title == a);
console.log(aInB);
您还可以includes与flatMap和一起使用Object.values:
let a = 'abc'
let b = [{title:'ccc'},{title:'abc'},{title:'ddd'}];
let aInB = b.flatMap(Object.values).includes(a) ? "Yes" : "No";
console.log(aInB);
没有flatMap或的版本flat(不受支持):
let a = 'abc'
let b = [{title:'ccc'},{title:'abc'},{title:'ddd'}];
let aInB = b.map(Object.values).reduce((a, c) => a.concat(c)).includes(a) ? "Yes" : "No";
console.log(aInB);
ES5 语法:
var a = 'abc'
var b = [{title:'ccc'},{title:'abc'},{title:'ddd'}];
var aInB = b.map(function(e) {
return Object.keys(e).map(function(key) {
return e[key];
});
}).reduce(function(a, c) {
return a.concat(c);
}).indexOf(a) > -1 ? "Yes" : "No";
console.log(aInB);
TA贡献2016条经验 获得超9个赞
您可以使用Array#find。
Array#find将返回匹配项,或者undefined如果没有找到匹配项,则您可以在if语句中使用结果。
let a = 'abc'
let b = [{title:'ccc'},{title:'abc'},{title:'ddd'}]
let c = b.find((d) => d.title === a);
if (c) {
return 'yes';
} else {
return 'no';
}
添加回答
举报