我想知道{title:'ccc'},{title: 'abc‘},{title:'ddd'}中是否有’abc‘
let a = 'abc'
let b = [{title:'ccc'},{title:'abc'},{title:'ddd'}]
if there is a in b{
return 'yes'
} else {
return 'no
}
//怎么做,怎么判断
发布于 2019-06-10 17:05:00
最简单的答案是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);
发布于 2019-06-10 17:04:03
Array.prototype.some()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
var a = 'abc';
var b = [
{value: 'def'},
{value: 'abc'},
{value: 'ghi'}
];
const result = b.some(x => x.value === a);
console.log(result);
发布于 2019-06-10 17:04:11
您可以使用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';
}
https://stackoverflow.com/questions/56523338
复制相似问题