应用 .includes() 遍历嵌套对象

Iterating through nested objects applying .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: true,
        id: -140
    }
}

我想遍历对象并使用 <String>.includes('o'); 查找包含字母 'o' 的任何对象名称 我尝试使用 obj.forEach(fn) 并遍历它们检查名称 属性 是否存在,然后检查 obj.name 是否包含 o 但是,我无法使用 forEach,因为我收到错误 obj.forEach is not a function.

有没有有效的方法来做到这一点?

对象不是数组,所以不能使用forEach。相反,迭代 keys/values/entries (无论你需要什么),检查对象上是否存在 .name 属性 并且是一个字符串,如果是,请使用 .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')
  ))
);