Search code examples
javascriptjavascript-objectsnested-loops

Iterating through nested objects applying .includes()


I have an object like this so for example:

const obj = 
{
    '140': {
        name: 'Jim',
        id: 140,
        link: 'http://a-website.com',
        hashKey: 'sdfsdgoihn21oi3hoh',
        customer_id: 13425
    },
    '183': {
        name: 'Foo',
        id: 183,
        link: 'http://a-website.com/abc',
        hashKey: 'xccxvq3z',
        customer_id: 1421
    },
    '143': {
        name: 'Bob',
        id: 143,
        link: 'http://a-website.com/123',
        hashKey: 'xcnbovisd132z',
        customer_id: 13651
    },
    '-40': {
        rgb: {
            b: 42,
            g: 114,
            r: 94
        },
        id: -40,
    },
    '-140': {
        rgb: {
            b: 77,
            g: 17,
            r: 55
        },
        done: true,
        id: -140
    }
}

I would like to iterate through the objects and look for any object's name that includes the letter 'o' using <String>.includes('o'); I tried to use obj.forEach(fn) and iterate through them checking if the name property exists and then check if the obj.name includes o however, I was unable to use forEach as I got the error obj.forEach is not a function.

Is there an efficient way of doing this?


Solution

  • Objects are not arrays, so you can't use forEach. Instead, iterate over the keys/values/entries (whatever you need), check to see if the .name property exists on the object and is a string, and if so, use .includes:

    const obj={'140':{name:'Jim',id:140,link:'http://a-website.com',hashKey:'sdfsdgoihn21oi3hoh',customer_id:13425},'183':{name:'Foo',id:183,link:'http://a-website.com/abc',hashKey:'xccxvq3z',customer_id:1421},'143':{name:'Bob',id:143,link:'http://a-website.com/123',hashKey:'xcnbovisd132z',customer_id:13651},'-40':{rgb:{b:42,g:114,r:94},id:-40,},'-140':{rgb:{b:77,g:17,r:55},done:!0,id:-140}};
    
    console.log(
      Object.entries(obj).filter(([key, { name }]) => (
        typeof name === 'string' && name.includes('o')
      ))
    );