【问题标题】:Iterating through nested objects applying .includes() [duplicate]迭代嵌套对象应用 .includes() [重复]
【发布时间】:2018-07-10 09:55:04
【问题描述】:

我有一个这样的对象,例如:

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。

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

【问题讨论】:

  • 将您现有的代码应用到您可以通过Object.keys(obj) 获取的数组中。
  • 仅供参考,你有lots of options

标签: javascript javascript-objects nested-loops


【解决方案1】:

对象不是数组,所以不能使用forEach。相反,遍历键/值/条目(无论您需要什么),检查对象上是否存在 .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')
  ))
);

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 2016-04-08
    • 2021-10-23
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2021-05-19
    • 2023-03-21
    相关资源
    最近更新 更多