admin管理员组文章数量:1334282
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
- 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
4 Answers
Reset to default 6You can use Array.prototype.map()
and Array.prototype.includes()
.
includes()
to check whethername
is present instrings
map()
to get a array with new values ofis
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)
本文标签: javascriptHow to compare array of objects and array of stringsStack Overflow
版权声明:本文标题:javascript - How to compare array of objects and array of strings? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742357030a2459617.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论