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)