我有一个从API获得的对象数组。属性名称是动态的(意味着我没有所有这些属性的详尽列表)。如何获得所有不同对象的数组?合同规定,如果键相等,则值也相等。我试着环顾四周,但没有发现完全像这个问题。
[ 20:31:28
{
'product-management': 'Product management'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
}
]
答案 0 :(得分:1)
将数组扩展为Object.assign()
,将所有对象合并为一个对象。由于所有对象的属性都是唯一的,因此重复项将仅保留一个键(和值)。然后将Object.entries()
转换为[key,value]对,并映射回单个对象:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([k, v]) => ({ [k]: v }))
console.log(result)
使用@Bergi's suggestion,您还可以在删除重复项的同时将其转换为更精巧的API:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([key, value]) => ({ key, value }))
console.log(result)