[英]How to merge two arrays of objects by key
我有两个 json 文件。 一个包含州名、缩写和 ID(“Estados.json”)。 另一个我有多个具有 ID、城市名称和相应 State 代码(“Cidades.json”)的对象。 我想要做的是合并两个基于 arrays 的,对于每个 state,其所有相应的城市都在一个新的密钥下。
预期的 output 是这样的:
[{
"ID": "1",
"Sigla": "AC",
"Nome": "Acre"
"Cidades":
{
"ID": 79,
"Nome": "Acrelândia",
"Estado": "1"},
{
"ID": "80",
"Nome": "Assis Brasil",
"Estado": "1"},
...,
{all the objects that have the same "Estado" key value 1}
}]
链接到 json 文件: https://github.com/felipefdl/cidades-estados-brasil-json
const j1 = `https://raw.githubusercontent.com/felipefdl/cidades-estados-brasil-json/master/Estados.json`; const j2 = `https://raw.githubusercontent.com/felipefdl/cidades-estados-brasil-json/master/Cidades.json`; (async () => { const Estados = await ((await fetch(j1)).json()); const Cidades = await ((await fetch(j2)).json()); Estados.forEach(e => { e.Cidades = Cidades.filter(c => e.ID === c.Estado); }); console.log(Estados[0]); // Estados now contains Cidades })();
这里我们使用 map 方法和 Object.assign 方法使用 id 合并对象数组。
function mergeArrayObjects(arr1,arr2){
return arr1.map((item,i)=>{
if(item.id === arr2[i].id){
//merging two objects
return Object.assign({},item,arr2[i])
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.