Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find values in array of object with another array of strings

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading