gpt4 book ai didi

javascript - 将对象的特定属性转换为对象数组

转载 作者:行者123 更新时间:2023-11-28 17:26:59 24 4
gpt4 key购买 nike

这是我原来的对象:

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(数据)但这会返回一个数组,末尾带有来自 Score 属性的 3

最佳答案

您可以使用Object.values() method 获取值的数组,然后使用 Array#filter() method 仅过滤其中的对象

这就是您的代码:

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);

关于javascript - 将对象的特定属性转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51324374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com