簡體   English   中英

遍歷嵌套的JSON對象數組並存儲為鍵值對

[英]Iterate through nested JSON object array and store as key-value pair

我必須遍歷此JSON:

{
  "data": 321563,
  "group": [
    {
      "added": 42421,
      "normal": {
        "x": 39,
        "y": "0.1300",
        "b": "0.4326",
        "c": "0.0552",
        "f": 166833
      },
      "j": "240313",
      "b": "0.2251",
      "a": "dda",
      "b": "0.101",
      "a": 922,
      "f": {
        "c": 39,
        "d": "0.263",
        "a": "2.8955",
        "h": "0.3211",
        "d": 274
      },
      "a": false,
      "k": 5,
      "w": "0.072",
      "d": "0.045",
      "e": 3
    },

我只希望j和k像鍵值對那樣存儲,例如"j":k

我需要循環所有這些,並將其存儲到文件中。

您可以使用地圖獲取新的項目數組,這不會影響舊的數組。

 const data = { "game_count": 8750, "sets": [ { "appid": "221540", "true_count": 9, "bgs_avg": "0.10", // Other data here }, { "appid": "123456", "true_count": 9, "bgs_avg": "0.20", // Other data here } ] } // Use "data.sets = data.sets.map(...)" to replace the data // The following will only assign to a new variable const newArray = data.sets.map(itm => { return {appid: itm.appid, true_count: itm.true_count} }) console.log(newArray) 

我們還可以通過使用data.sets = data.sets.map(...)data.sets = data.sets.map(...)數據並將其直接分配回原始覆蓋,如下所示:

 const data = { "game_count": 8750, "sets": [ { "appid": "221540", "true_count": 9, "bgs_avg": "0.10", // Other data here }, { "appid": "123456", "true_count": 9, "bgs_avg": "0.20", // Other data here } ] } data.sets = data.sets.map(itm => { return {appid: itm.appid, true_count: itm.true_count} }) console.log(data) 

在簡單的javascript中,這應該有效

let newObj = {}
for(let i=0; i<obj.group.length; i++){
  newObj[obj.group[i].j] = obj.group[i].k 
}

其中“ obj”是您的對象

newObj將是您的新對象,其中將包含所有鍵值對

暫無
暫無

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

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