Requirement – I would like to fetch labels from the array of object if the id exists which will be fetched from another array. If that id don’t exists, I would like to return that id from the second array.
var objectVar = [{ id: '1', label: 'One' }, { id: '2', label: 'Two' }, { id: '3', label: 'Three' }];
var arrVar = ['1', '2', '3', '4'];
Here, as 1,2,3 exists I would like to return the labels of it and since 4 doesn’t exist in array of object, I would like to return 4. This can be stored in a new Array.
Expected result might look like this –
result = ['One', 'Two', 'Three', '4'];
>Solution :
let objectVar = [{ id: '1', label: 'One' }, { id: '2', label: 'Two' }, { id: '3', label: 'Three' }];
let arrVar = ['1', '2', '3', '4'];
let output = arrVar.map(a => {
let matched = objectVar.filter(x => x.id == a);
if(matched.length > 0) {
return matched[0].label;
}
return a;
});
console.log(output)