我有一个这样的对象,例如:
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,但是由于出现错误obj.forEach不是函数,所以我无法使用forEach。
是否有一种有效的方法?
答案 0 :(得分: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')
))
);