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

Loop through array of objects, if value exists, return another value

With the information below I am trying loop through cards, if there is a nested object of helper, return that objects title. But am either receiving undefined or errors. I was thinking maybe reduce would be viable here?

Sample Array:

cards: [
    0: {
        title: 'Something',
        logo: 'logo link here',
    },
    1: {
        title: 'Something 2',
        logo: 'logo link here',
        helper: {
            text: 'helper text',
        },
    },
    2: {
        title: 'Something 3',
        logo: 'logo link here',
    },
]

code:

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

cards.filter((item) => {
    if (item.helper) setHelperActive({...helperActive, item.title: true}) 
})

>Solution :

Using .filter() and checking if the object has a prop named helper. In case of multiple objects matching the criteria, their title’s will be joined as a comma-separated string.

Snippet

let cards = [
    {
        title: 'Something',
        logo: 'logo link here',
    },
    {
        title: 'Something 2',
        logo: 'logo link here',
        helper: {
            text: 'helper text',
        },
    },
    {   
        title: 'Something',
        logo: 'logo link here',
    },
    {
        title: 'Something 4',
        logo: 'logo link here',
        helper: {
            text: 'helper text',
        },
    },
]

// to list titles from all matching objects as a comma-separated string
console.log(cards.filter(ob => 'helper' in ob).map(({ title }) => title).join());

// suppose only the first matched object's title is required
console.log(cards.find(ob => 'helper' in ob)?.title ?? 'no match found');
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