How to transpose a javascript object into a key/va

2019-01-06 19:59发布

This question already has an answer here:

Given a JavaScript object, how can I convert it into an array of objects (each with key, value)?

Example:

var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' }

resulting like:

[
  { key: 'firstName', value: 'John' },
  { key: 'lastName', value: 'Doe' },
  { key: 'email', value: 'john.doe@gmail.com' }
]

8条回答
虎瘦雄心在
2楼-- · 2019-01-06 20:42

The previous answer lead me to think there is a better way...

Object.keys(data).map(function(key) {
  return { key, value: data[key] };
});

or in ES6 using arrow functions:

Object.keys(data).map((key) => ({ key, value: data[key] }));
查看更多
三岁会撩人
3楼-- · 2019-01-06 20:45

You can just iterate over the object's properties and create a new object for each of them.

var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' };
var result = [];

for(var key in data)
{
    if(data.hasOwnProperty(key))
    {
        result.push({
            key: key,
            value: data[key]
        });
    }
}
查看更多
登录 后发表回答