我如何找到 'abc' 在数组中 [{title:'ccc'},{title:'abc'}

我想知道 [{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

}

//我该怎么做以及如何判断


慕森卡
浏览 163回答 3
3回答

白猪掌柜的

最简单的答案是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);

慕沐林林

您可以使用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';}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript