我有一个包含重复值的数组,我想将其转换为仅包含唯一值的对象,并将数组中的值用作键和值。
在下面的示例中,我可以创建一个仅包含唯一值的对象,但我不知道如何找到一个对象,而不是
{
0: "Rookie Ticket Variation RPS",
1: "Veteran Ticket Variation RPS",
2: "Optics Season Ticket Red"
}
看起来像
{
RookieTicketVariationRPS: "Rookie Ticket Variation RPS",
VeteranTicketVariationRP: "Veteran Ticket Variation RPS",
OpticsSeasonTicketRed: "Optics Season Ticket Red"
}
这里的区别在于:
let arr = [
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Rookie Ticket Variation RPS",
},
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Veteran Ticket Variation RPS",
},
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Rookie Ticket Variation RPS",
},
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Optics Season Ticket Red",
}
]
let set = [...new Set(arr.map((o) => o.variation))]
let newarray= { ...set}
console.log(newarray)
谁能建议正确的方法来做到这一点?
答案 0 :(得分:2)
获得 yield
字符串后,通过删除空格将其映射到对象以构造键并将其传递给 otoMotoCarObject(scrapy.Item)
:
response
答案 1 :(得分:0)
您可以使用.reduce
:
const arr = [
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Rookie Ticket Variation RPS",
},
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Veteran Ticket Variation RPS",
},
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Rookie Ticket Variation RPS",
},
{
"manufacturer":"Panini",
"brand":"Contenders",
"variation":"Optics Season Ticket Red",
}
];
const newarray= arr.reduce((acc,{variation}) => {
acc[variation.replace(/\s/g, '')] = variation;
return acc;
}, {});
console.log(newarray);