How to transpose a javascript object into a key/value array

本秂侑毒 提交于 2020-01-16 09:05:31

问题


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' }
]

回答1:


var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' }
var output = Object.entries(data).map(([key, value]) => ({key,value}));

console.log(output);

Inspired By this post




回答2:


Using map function

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

var result = Object.keys(data).map(key => ({ key, value: data[key] }));

console.log(result);
    



回答3:


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]
        });
    }
}



回答4:


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] }));



回答5:


Just make your life easier and use es6 syntax with a map

    var output = Object.keys(data).map(key => {
      return {
        key: key,
        value: data[key]
      };
    })



回答6:


var result = [];
for(var k in data) result.push({key:k,value:data[k]});



回答7:


An alternative method for doing this that works on multi level objects and does not use recursion.

var output = []

    var o = {
      x:0,
      y:1,
      z:{
        x0:{
          x1:4,
          y1:5,
          z1:6
        },
        y0:2,
        z0:[0,1,2],
      }
    }

    var  defer = [ [ o ,[ '_root_' ] ] ]
    var _defer = []


    while(defer.length){

    var current = defer.pop()

    var root    = current[1]
        current = current[0]


      for(var key in current ){

        var path = root.slice()
            path.push(key)

        switch( current[key].toString() ){
        case '[object Object]':
          _defer.push( [ current[key] , path ] )
        break;;
        default:
         output.push({
          path  : path ,
          value : current[key]
         })
        break;;
        }
      }

      if(!defer.length)
          defer = _defer.splice(0,_defer.length)
    }

[
{ path: [ '_root_', 'x' ], value: 0 },
{ path: [ '_root_', 'y' ], value: 1 },
{ path: [ '_root_', 'z', 'y0' ], value: 2 },
{ path: [ '_root_', 'z', 'z0' ], value: [ 0, 1, 2 ] },
{ path: [ '_root_', 'z', 'x0', 'x1' ], value: 4 },
{ path: [ '_root_', 'z', 'x0', 'y1' ], value: 5 },
{ path: [ '_root_', 'z', 'x0', 'z1' ], value: 6 }
]



回答8:


Or go wild and make the key and value keys customizable:

module.exports = function objectToKeyValueArray(obj, keyName = 'key', valueName = 'value') {
    return Object
        .keys(obj)
        .filter(key => Object.hasOwnProperty.call(obj, key))
        .map(key => {
            const keyValue = {};
            keyValue[keyName] = key;
            keyValue[valueName] = obj[key];

            return keyValue;
        });
};



回答9:


I would say to use npm package flat. works amazing for nested objects and arrays.

var flatten = require('flat')

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
})

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a.b.c': 2
// }


来源:https://stackoverflow.com/questions/58075635/can-i-change-the-single-object-of-json-data-into-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!