簡體   English   中英

如何按鍵合並對象的兩個arrays

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM