如何将javascript对象转换为键/值数组

时间:2016-04-04 19:46:50

标签: javascript arrays javascript-objects

给定一个JavaScript对象,如何将其转换为对象数组(每个对象都有键值)?

示例:

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

结果如:

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

10 个答案:

答案 0 :(得分:40)

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

console.log(output);

灵感来自post

答案 1 :(得分:13)

使用map功能

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

答案 2 :(得分:10)

您可以迭代对象的属性并为每个属性创建一个新对象。

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

答案 3 :(得分:5)

之前的回答让我觉得有更好的方法......

apf <- approxfun( x=sort(bdat$time), y=seq(length( bdat$time))  ,rule=2)
apf( adat$time)
#[1] 1.000 3.750 3.875
round( apf( adat$time))
#[1] 1 4 4

或在ES6中使用箭头功能:

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

答案 4 :(得分:5)

让您的生活更轻松,并将es6语法与地图一起使用

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

答案 5 :(得分:3)

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

答案 6 :(得分:1)

执行此操作的一种替代方法,该方法适用于多级对象,并且不使用递归。

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

答案 7 :(得分:0)

或狂野地使keyvalue键可自定义:

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

答案 8 :(得分:0)

我会说要使用npm package flat。 对于嵌套对象和数组,效果惊人。

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

答案 9 :(得分:-2)

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

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

console.log(obj);