Rob Brander
Rob Brander

Reputation: 3781

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

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: '[email protected]' }

resulting like:

[
  { key: 'firstName', value: 'John' },
  { key: 'lastName', value: 'Doe' },
  { key: 'email', value: '[email protected]' }
]

Upvotes: 47

Views: 88794

Answers (11)

Sudhanshu Sharma
Sudhanshu Sharma

Reputation: 192

const array = [
    { key: "key1", value: "value1" },
    { key: "key2", value: "value2" },
];

const obj = Object.fromEntries(array.map(item => [item.key, item.value]));

console.log(obj);

Upvotes: 0

Sudhanshu Sharma
Sudhanshu Sharma

Reputation: 192

const array = [
    { key: "key1", value: "value1" },
    { key: "key2", value: "value2" },
];

const obj = Object.fromEntries(array.map(item => [item.key, item.value]));

console.log(obj);

Upvotes: -2

Kathan Shah
Kathan Shah

Reputation: 1755

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
// }

Upvotes: -2

Rob Brander
Rob Brander

Reputation: 3781

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

Upvotes: 7

James Andino
James Andino

Reputation: 25779

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

Upvotes: 1

atiq1589
atiq1589

Reputation: 2327

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

console.log(output);

Inspired By this post

Upvotes: 113

mandarin
mandarin

Reputation: 1386

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

Upvotes: 1

isvforall
isvforall

Reputation: 8926

Using map function

var data = { firstName: 'John', lastName: 'Doe', email: '[email protected]' };

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

console.log(result);
    

Upvotes: 24

Rob Wilkinson
Rob Wilkinson

Reputation: 296

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

Upvotes: 5

Alexander Popov
Alexander Popov

Reputation: 836

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: '[email protected]' };
var result = [];

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

Upvotes: 10

Gene R
Gene R

Reputation: 3744

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

Upvotes: 3

Related Questions