簡體   English   中英

在數組json中的單個對象中轉換多個相同的鍵對象

[英]Converting multiple same key object in single object within array json

我在下面有這個json

[
  {"animal": "cat"},
  {"animal": "dog"},
  {"animal": "elephant"},
  {"vehicle": "car"},
  {"vehicle": "bike"},
  {"vehicle": "truck"},
  {"toys": "a1"},
  {"toys": "a2"},
  {"toys": "a3"}
]

我預期的 json 響應是:

[
  {"animal": "cat", "vechile": "car", "toys": "a1"},
  {"animal": "dog", "vechile": "bike", "toys": "a2"},
  {"animal": "elephant", "vechile": "truck", "toys": "a3"}
]

我嘗試了以下程序,但沒有給我預期的輸出,我想制作一個可以比較的數組並相應地添加:

var myGlobalArr = []
var globalObject = {}

for (var i = 0; i < mainArr.length; i++)
{
    if (Object.keys(mainArr[i])[0] == Object.keys(myGlobalArr[i])[0])
    {
        globalObject[Object.keys(mainArr[i])[0]] = globalObject[Object.values(mainArr[i])[0]]
    }
}

console.log(myGlobalArr)

幫助將不勝感激!

#編輯:

它將是3塊。

您可以使用Array.reduce() 來做到這一點。 reduce每次迭代中,您可以使用對象modulus 3 ( idx % 3 ) 的當前索引檢查最終數組的哪個索引放置您的數據:

 const input = [ {"animal": "cat"}, {"animal": "dog"}, {"animal": "elephant"}, {"vehicle": "car"}, {"vehicle": "bike"}, {"vehicle": "truck"}, {"toys": "a1"}, {"toys": "a2"}, {"toys": "a3"} ]; let res = input.reduce((acc, curr, idx) => { let [[k, v]] = Object.entries(curr); acc[idx % 3] = acc[idx % 3] || {}; acc[idx % 3][k] = v; return acc; }, []) console.log(res);
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}

您可以使用一個哈希表來處理結果集相同鍵的正確索引。

這適用於任意數量的對象/屬性和順序,只要相同的屬性是有序的。

 var data = [ { animal: "cat" }, { animal: "dog" }, { animal: "elephant" }, { vehicle: "car" }, { vehicle: "bike" }, { vehicle: "truck" }, { toys: "a1" }, { toys: "a2" }, { toys: "a3" }], indices = {}, result = data.reduce((r, o) => { var key = Object.keys(o)[0]; indices[key] = indices[key] || 0; Object.assign(r[indices[key]] = r[indices[key]] || {}, o); indices[key]++; return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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