我有两个对象数组(如果我使用的术语不正确,请原谅我。我是JS的新手)。数组dataset
和dataset2
具有带有公共键的对象id
。我想合并每个对象以形成合并对象的新数组。如下图datasetCombined
所示。
dataset = [{
"State": "AL",
"id": 1000,
"name": "Alabama",
"percent_educated": 24},
{
"State": "AL",
"id": 1001,
"name": "Autauga County",
"percent_educated": 24.6},
{
"State": "AL",
"id": 1003,
"name": "Baldwin County",
"percent_educated": 29.5
}]
dataset2 = [{
"id": 1000,
"qualified_professionals": "64,767,787",
"high_school": "58,820,411",
"middle_school_or_lower": "27,818,380" },
{
"id": 1001,
"qualified_professionals": "783,076",
"high_school": "1,009,593",
"middle_school_or_lower": "496,036" },
{
"id": 1003,
"qualified_professionals": "8,968",
"high_school": "12,519",
"middle_school_or_lower": "4,528"
}]
所需输出:
datasetCombined = [{
"State": "AL",
"id": 1000,
"name": "Alabama",
"percent_educated": 24,
"qualified_professionals": "64,767,787",
"high_school": "58,820,411",
"middle_school_or_lower": "27,818,380"},
{
"State": "AL",
"id": 1001,
"name": "Autauga County",
"percent_educated": 24.6,
"qualified_professionals": "783,076",
"high_school": "1,009,593",
"middle_school_or_lower": "496,036"},
{
"State": "AL",
"id": 1003,
"name": "Baldwin County",
"percent_educated": 29.5,
"qualified_professionals": "8,968",
"high_school": "12,519",
"middle_school_or_lower": "4,528"
}]
在错误地理解了您的问题之后,我花了一些时间并为您构建了此示例,以便您根据Id合并两个数组。
let dataset = [{
"State": "AL",
"id": 1000,
"name": "Alabama",
"percent_educated": 24
},
{
"State": "AL",
"id": 1001,
"name": "Autauga County",
"percent_educated": 24.6
},
{
"State": "AL",
"id": 1003,
"name": "Baldwin County",
"percent_educated": 29.5
}
];
let dataset2 = [{
"id": 1000,
"qualified_professionals": "64,767,787",
"high_school": "58,820,411",
"middle_school_or_lower": "27,818,380"
},
{
"id": 1001,
"qualified_professionals": "783,076",
"high_school": "1,009,593",
"middle_school_or_lower": "496,036"
},
{
"id": 1003,
"qualified_professionals": "8,968",
"high_school": "12,519",
"middle_school_or_lower": "4,528"
}
];
// create a function to reduce your arrays
let reducer = function(accumulator, currentValue, currentIndex, array) {
// check if the item already exists in the array
let found = accumulator.find((item) => item.id == currentValue.id);
if (found) {
// if it exists then use assign to merge the two values
Object.assign(found, currentValue)
} else {
// doesn't exist, just add it to the array
accumulator.push(currentValue);
}
return accumulator;
}
let datasetCombined = [];
dataset.reduce(reducer, datasetCombined);
dataset2.reduce(reducer, datasetCombined);
console.log(datasetCombined);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句