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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36411566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:01:11  来源:igfitidea点击:

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

javascriptarraysjavascript-objects

提问by Rob Brander

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

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

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

回答by atiq1589

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

灵感来自这篇文章

回答by isvforall

Using mapfunction

使用map功能

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

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

console.log(result);
    

回答by Alexander Popov

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

回答by Rob Brander

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:

或者在 ES6 中使用箭头函数:

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

回答by Rob Wilkinson

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

只是让你的生活更轻松,并在地图上使用 es6 语法

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

回答by Gene R

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

回答by James

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

回答by mandarin

Or go wild and make the keyand valuekeys customizable:

或者疯狂地使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;
        });
};

回答by Kathan Shah

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

我会说使用 npm 包平面。对嵌套对象和数组效果很好。

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