简体   繁体   English

如何将一个对象转换为一个对象数组?

[英]How to transform an object into an array of objects?

I am looking for a way to transform an object into an array of objects, and remove the first unique key. 我正在寻找一种将对象转换为对象数组并删除第一个唯一键的方法。

How can I make this: 我该如何做:

{f56hdhgf54: {name: 'Sam', age: 34}, h65fg9f7d: {name: 'John', age: 42}}

into this: 到这个:

[{name: 'Sam', age: 34}, {name: 'John', age: 42}]

so I can .map through it like this: 所以我可以这样.map它:

result.map((person) => {
   console.log(person.name, person.age)
})

You can use Object.keys() to get array of keys and then map() to change keys to values or in this case objects. 您可以使用Object.keys()获取键数组,然后使用map()将键更改为值或在这种情况下为对象。

 var obj = {f56hdhgf54: {name: 'Sam', age: 34}, h65fg9f7d: {name: 'John', age: 42}} var result = Object.keys(obj).map(function(e) { return obj[e]; }); console.log(result); 

Another approach will be using lodash map function to transform the data, ie 另一种方法是使用lodash映射函数来转换数据,即

let data = {
   "f56hdhgf54": {
      "name": "Sam",
       "age": 34
    },
    "h65fg9f7d": {
      "name": "John",
      "age": 42
    }
}


let result = _(data)
  .map((value, key) => (
    value
  ))


 // result
 [
   {
      "name": "Sam",
      "age": 34
   },
   {
      "name": "John",
      "age": 42
   }
]

You can use the Lodash Online tester https://codepen.io/travist/full/jrBjBz to test the code 您可以使用Lodash在线测试仪https://codepen.io/travist/full/jrBjBz来测试代码

Using Jquery solution of this question 使用jQuery解决这个问题

var xyz = [];
    var abcd = {f56hdhgf54: {name: 'Sam', age: 34}, h65fg9f7d: {name: 'John', age: 42}}
    $.each(abcd,function(i,data){

    xyz .push(data);

    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM