如何从字典中提取项目

时间:2019-04-05 16:45:27

标签: javascript reactjs

我有一本看起来像这样的字典:

"Player Details": {
    "Sally Smith": {
        "player_id": 2,
        "color_one": "blue",
        "color_two": "red"
    },
    "John Smith": {
        "player_id": 4,
        "color_one": "white",
        "color_two": "black"
    }
}

我需要它进入数组并像这样结束:

"Player details": [
    {
        "player_id": "2",
        "color_one": "blue",
        "color_two": "red"
    },
    {
        "player_id": "4",
        "color_one": "white",
        "color_two": "black"
    }
]

我尝试了以下操作,但“值”仍然存在:

Object.entries(myDictionary).forEach(([key, value]) => {
   newArray.push({value})
});

我觉得我快到了,有人可以帮忙吗?

3 个答案:

答案 0 :(得分:3)

只需使用Object.values方法从对象中获取值,该方法将在数组中返回对象属性值。

let data = {
  "Player Details": {
    "Sally Smith": {
      "player_id": 2,
      "color_one": "blue",
      "color_two": "red"
    },
    "John Smith": {
      "player_id": 4,
      "color_one": "white",
      "color_two": "black"
    }
  }
}


let res = {
  'Player Details': Object.values(data['Player Details'])
};

// or in case you justt need the array then 
let res1 = Object.values(data['Player Details']);

console.log(res)
console.log(res1)

仅供参考::由于您的媒体资源中有空格,因此您不能使用dot notation来访问媒体资源,而不能使用bracket notation

答案 1 :(得分:1)

您需要遍历myDictionary["Player Details"]并将value推入newArray而不是{ value }

或者您也可以使用Object.values

Object.values(myDictionary["Player Details"])

const myDictionary = {
  "Player Details": {
    "Sally Smith": {
        "player_id": 2,
        "color_one": "blue",
        "color_two": "red"
    },
    "John Smith": {
        "player_id": 4,
        "color_one": "white",
        "color_two": "black"
    }
  }
}

const newArray = [];

Object.entries(myDictionary["Player Details"]).forEach(([key, value]) => {
   newArray.push(value)
});

console.log(newArray);

// Or a single one liner

console.log(Object.values(myDictionary["Player Details"]));

答案 2 :(得分:1)

您可以简单地使用Object.values

let obj = {"Player Details": {
    "Sally Smith": {
        "player_id": 2,
        "color_one": "blue",
        "color_two": "red"
    },
    "John Smith": {
        "player_id": 4,
        "color_one": "white",
        "color_two": "black"
    }
}}
let op = {'Player Details' : Object.values(obj['Player Details'])}

console.log(op)