如何找到数组[{title:'ccc'},{title:'abc'},{title:'ddd',}]中的'abc'

时间:2019-06-10 09:00:14

标签: javascript arrays object ecmascript-6

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

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

6 个答案:

答案 0 :(得分:2)

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);

答案 1 :(得分:2)

最简单的答案是some

let a = 'abc'
let b = [{title:'ccc'},{title:'abc'},{title:'ddd'}];
let aInB = b.some(({ title }) => title == a);
console.log(aInB);

您还可以将includesflatMapObject.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);

没有flatMapflat的版本(不受很好的支持):

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);

答案 2 :(得分:1)

您可以使用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';
}

答案 3 :(得分:0)

var exist = b.find(function(element) {
  return element.title === a;
});

如果您知道要查看产权标题,那应该是您的解决方案

答案 4 :(得分:0)

  for (i=0; i<b.length; i++){
       if(i.title == a){
       console.log('yes')
       }
  }

答案 5 :(得分:0)

var a = 'ccc'
var b = [{title:'ccc'},{title:'abc'},{title:'ddd'}];

function presentAsTitle(a, b) {
    var flag = false;
    for (var i=0; i<=b.length; i++) {
        var item = b[i];
        if (item.title === a) {
            flag = true;
            break;
        }
    }
    return flag;
}