这是我的原始对象
Data = {
aesthetic: {
heritage: 'aesthetic',
description: 'sdokjosk',
value: 5
},
architectural: {
heritage: 'architectural',
description: 'doodsjdj',
value: 1
},
historical: {
heritage: 'historical',
description: 'dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ',
value: 4
},
score: 3
};
我想编写一个遍历对象的函数,并将仅带有“继承”,“描述”和“值”的属性转换为如下所示的数组:
[{
"heritage": "aesthetic",
"description": "sdokjosk",
"value": 5
},
{
"heritage": "architectural",
"description": "doodsjdj",
"value": 1
},
{
"heritage": "historical",
"description": "dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ",
"value": 4
}
]
这是我尝试过的:
Object.values(Data)
但这会返回一个数组,其末尾的score属性为3
答案 0 :(得分:2)
您可以使用 Object.values()
method 获取值array
,然后使用 Array#filter()
method 仅过滤其中的对象。< / p>
这应该是您的代码:
var result = Object.values(Data).filter(x => typeof x == 'object');
演示:
这是一个有效的演示代码段:
var Data = {
aesthetic: {
heritage: 'aesthetic',
description: 'sdokjosk',
value: 5
},
architectural: {
heritage: 'architectural',
description: 'doodsjdj',
value: 1
},
historical: {
heritage: 'historical',
description: 'dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ',
value: 4
},
score: 3
};
var result = Object.values(Data).filter(x => typeof x == 'object');
console.log(result);
答案 1 :(得分:1)
如果要检查提到的所有键,请使用以下方法:
Object.values(Data).filter(function(data){return data["heritage"] && data["description"] && data["value"]})