简体   繁体   中英

How to merge two arrays of objects by key

I have two json files. One with the name of the States, its abbreviation and an ID ("Estados.json"). The other one i have multiple objects with ID, city names and a corresponding State code ("Cidades.json"). What i'm trying to do is to merge both arrays based, getting, for each state, all its corresponding cities under a new key.

The expected output is something like this:

[{
"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}

      }]

Link to the both json files: 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 })();

Here we are the using map method and Object.assign method to merge the array of objects by using 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])
       }
   })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM