gpt4 book ai didi

javascript - 将对象内的相同 id 连接到一个对象数组

转载 作者:行者123 更新时间:2023-11-28 16:42:03 24 4
gpt4 key购买 nike

我的数据结构如下:

let siteLists = [
{
"data": {
"client_id": 29
},
"all_branch": 1,
"value": 29,
"label": "A Site"
},
{
"data": {
"client_id": 23,
},
"all_branch": 0,
"value": 91,
"label": "B-1 Site"
},
{
"data": {
"client_id": 23,
},
"all_branch": 0,
"value": 86,
"label": "B-2 Site"
},
{
"data": {
"client_id": 10
},
"all_branch": 1,
"value": 10,
"label": "C Site"
}
];

我需要将具有相同 data.client_id 值的上述对象连接到一个包含所有分支值的对象中。

预期结果:

[
{
id: 29,
branches: [],
all_branch:1
},
{
id: 23,
branches: [91,86],
all_branch:0
},
{
id: 10,
branches: [],
all_branch:1
}
]

我尝试了以下代码,但结果不符合预期结果...

let populate = [...siteLists.map(item => {
return item.all_branch === 1 ? {
all_placement: 1,
placement_id: item.data.client_id,
branch_id: []
} : {
all_placement: 0,
placement_id: item.data.client_id,
branch_id: [item.value]
}
})];

最佳答案

这应该可行,但可能不是最佳的。我还冒昧地将值添加到分支数组中,而不是将其留空。

let siteLists = [{
"data": {
"client_id": 29
},
"all_branch": 1,
"value": 29,
"label": "A Site"
},
{
"data": {
"client_id": 23,
},
"all_branch": 0,
"value": 91,
"label": "B-1 Site"
},
{
"data": {
"client_id": 23,
},
"all_branch": 0,
"value": 86,
"label": "B-2 Site"
},
{
"data": {
"client_id": 10
},
"all_branch": 1,
"value": 10,
"label": "C Site"
}
];
var resultarray = []; //expected result
var branchId = []; //stores an object to map the branch ID and the array index to keep track of duplicate IDs
var count = 0; //keeps track of the current array Index
siteLists.forEach(element => { //for loop to loop through siteList array
var resultObj = new Object(); //stores the temporary result Object
var id = element.data.client_id;
var status = false; //keeps track of if it is a duplicate ID
if (count != 0) {
branchId.forEach(obj => { //for loop to check for duplicate ID (will only run after the first iteration of result loop)
if (obj.id === id) { //checks if the ID matches
var index = obj.index;
var value = element.value;
resultarray[index].branches.push(obj.value);//pushes the matched ID value
resultarray[index].branches.push(value); //Pushes value to branches array if ID is duplicate
status = true;
}
})
}
if (status == false) {
var branchObj = {
'id': id,
'index': count,
'value':element.value
}
var allBranch = element.all_branch;
//var value = element.value; //uncomment if you need value in the resultObj when id does not match
branchId.push(branchObj);
resultObj.id = id;
resultObj.branches = [];
//resultObj.branches.push(value);//uncomment if you need value in the resultObj when id does not match
resultObj.all_branch = allBranch;
resultarray.push(resultObj);
count = count + 1;
} else {
status = false;
}

})
console.log(resultarray);

关于javascript - 将对象内的相同 id 连接到一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61025925/

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