我有一个像这样的对象,例如:
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) 并迭代它们检查 name 属性是否存在,然后检查 obj.name 是否包含 o 但是,我无法使用 forEach,因为我收到错误 obj.forEach is not a function .
有没有有效的方法来做到这一点?
最佳答案
对象不是数组,因此不能使用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')
))
);
关于javascript - 应用 .includes() 迭代嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51262230/