最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to compare array of objects and array of strings? - Stack Overflow

programmeradmin1浏览0评论

I need to pare two arrays:

var objects = [{name: 'a', is: false}, {name: 'b', is: false}, {name: 'c', is: false}];
var strings = ['a', 'b'];

if object from objects is equal one of string from strings change field is to true, but I have no idea how I can do it

I need to pare two arrays:

var objects = [{name: 'a', is: false}, {name: 'b', is: false}, {name: 'c', is: false}];
var strings = ['a', 'b'];

if object from objects is equal one of string from strings change field is to true, but I have no idea how I can do it

Share Improve this question edited Mar 27, 2019 at 11:49 Marius 59k35 gold badges135 silver badges151 bronze badges asked Mar 27, 2019 at 11:44 vikvarvikvar 531 silver badge3 bronze badges 1
  • 1 When asking a question, It would be always nice to a have a piece of code that you have tried. – Kiren S Commented Mar 27, 2019 at 14:20
Add a ment  | 

4 Answers 4

Reset to default 6

You can use Array.prototype.map() and Array.prototype.includes().

  • includes() to check whether name is present in strings
  • map() to get a array with new values of is property

var objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
var strings = ['a','b'];

let res = objects.map(x => ({...x,is:strings.includes(x.name)}))

console.log(res)

You could iterate over objects array and use indexOf to check if the current object's name property is present in the strings array

var objects = [{name:'a',is:false},{name:'b',is:false},{name:'c',is:false}];
var strings = ['a','b'];

objects.forEach(function(obj) {
    if (strings.indexOf(obj.name)!=-1) obj.is = true;
})

console.log(objects);

you can use Array.From

   var objects = [{name: 'a', is: false}, {name: 'b', is: false}, {name: 'c', is: false}];
   var strings = ['a', 'b'];

  var result = Array.from(objects, (o)=>{  return  {...o, is:strings.includes(o['name'])}; });

   console.log(result);

Hope this helps you !

Expanding on the accepted answer above. Here is how you can then filter and return an array of the names that matched.

  var objects = [{
      name: 'a',
      is: false
    }, {
      name: 'b',
      is: false
    }, {
      name: 'c',
      is: false
    }];
    var strings = ['a', 'b'];
    
    var matchedNames = objects.map((item) => ({...item, display: strings.includes(item.name)})).filter(item => item.display == true).map(({name}) => name)
    
    console.log(matchedNames)
发布评论

评论列表(0)

  1. 暂无评论