javascript - 如何从字典中提取项目

标签 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})
});

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

最佳答案

只需使用 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 .

关于javascript - 如何从字典中提取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540044/

相关文章:

javascript - 使用 Passport.js 获取 Facebook 个人资料的链接

javascript - 如何修复拖放 JavaScript

javascript - 未捕获的 ReferenceError : is not defined at HTMLButtonElement. onclick

node.js - Webpack 错误 : Invalid configuration object. Webpack 已使用与 API 模式不匹配的配置对象初始化

reactjs - Material UI makeStyles 不会更改所有元素的 css 属性

ruby-on-rails - 过滤器链停止为 :verify_signed_out_user rendered or redirected error when making a delete fetch in Rails Devise

javascript - for循环中的promise.resolve()返回未定义

javascript - Angular 2/5 - 从选择中获取数字数据时遇到问题

javascript - 在 jsdom 测试中卸载/销毁组件

javascript - 如果我也可以做得更简单,那么 Object.defineProperty 有什么用?