gpt4 book ai didi

javascript - 在 Javascript 数组中排列一个重复对象以生成一个值

转载 作者:行者123 更新时间:2023-12-03 00:04:24 26 4
gpt4 key购买 nike

我正在尝试排列我当前的对象,如下所示

var myValues = [
{
client: "FIRE",
firstname: "Test",
id: "test@fire.com",
arrangeid: "FIREFOX",
region: "FOP",
secondname: "Testy",
status: "Approved"
},
{
client: "FIRE",
firstname: "Test",
id: "test@fire.com",
arrangeid: "BUZZZZZZ",
region: "FOP",
secondname: "Testy",
status: "Approved"
},
{
client: "PANTER",
firstname: "Panty",
id: "panty@panter.com",
arrangeid: "PANTER",
region: "PAN",
secondname: "mc panty",
status: "Approved"
},
{
client: "BAT",
firstname: "Bruce",
id: "bat@bat.com",
arrangeid: "BLACKBAT",
region: "BLK",
secondname: "Wyne",
status: "Approved"
}

]

所以我得到了这个对象,前两个ID是相同的,但它们有不同的arrangeid。我希望能够加入他们,将他们聚集在一起。对象看起来像这样:

    var myValues = [
{
client: "FIRE",
firstname: "Test",
id: "test@fire.com",
arrangeid: ["BUZZZZZZ", "FIREFOX"],
region: "FOP",
secondname: "Testy",
status: "Approved"
},
{
client: "PANTER",
firstname: "Panty",
id: "panty@panter.com",
arrangeid: ["PANTER"],
region: "PAN",
secondname: "mc panty",
status: "Approved"
},
{
client: "BAT",
firstname: "Bruce",
id: "bat@bat.com",
arrangeid: ["BLACKBAT"],
region: "BLK",
secondname: "Wyne",
status: "Approved"
}

]

我有一个jsfidle here ,我在那里得到了一个结果。能不能做得更好、更干净。我是否正确地对待它?

最佳答案

您可以使用reduce , Object.values() spread syntax像这样:

var myValues = [{client:"FIRE",firstname:"Test",id:"test@fire.com",arrangeid:"FIREFOX",region:"FOP",secondname:"Testy",status:"Approved"},{client:"FIRE",firstname:"Test",id:"test@fire.com",arrangeid:"BUZZZZZZ",region:"FOP",secondname:"Testy",status:"Approved"},{client:"PANTER",firstname:"Panty",id:"panty@panter.com",arrangeid:"PANTER",region:"PAN",secondname:"mc panty",status:"Approved"},{client:"BAT",firstname:"Bruce",id:"bat@bat.com",arrangeid:"BLACKBAT",region:"BLK",secondname:"Wyne",status:"Approved"}];

const merged = myValues.reduce((acc, a) => {
acc[a.client] = acc[a.client] || { ...a, arrangeid: [] };
acc[a.client].arrangeid.push(a.arrangeid);
return acc;
},{})

const output = Object.values(merged);
console.log(output)

累加器是一个对象,以每个唯一的客户端作为其键,以便更容易对它们进行分组。

{
"FIRE": {
"client": "FIRE",
"firstname": "Test",
"id": "test@fire.com",
"arrangeid": [ "FIREFOX", "BUZZZZZZ" ],
"region": "FOP",
"secondname": "Testy",
"status": "Approved"
},
"PANTER": {
"client": "PANTER",
"id": "panty@panter.com",
"arrangeid": [
"PANTER"
],
...
}
...
}

关于javascript - 在 Javascript 数组中排列一个重复对象以生成一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55031069/

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