JavaScript / Node.JS 将对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19091365/
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-10-27 14:18:27  来源:igfitidea点击:

JavaScript / Node.JS to convert an object into array

javascriptarrays

提问by Loser Coder

I have an object that looks like this:

我有一个看起来像这样的对象:

[
  {'el': 123},
  {'el': 234}, 
  {'el': 345}
]

I would like to convert this to an array that holds just the values, and remove the extra 'el' inside:

我想将其转换为仅包含值的数组,并删除内部额外的“el”:

var myArray = [ 123, 234, 345]; 

Is there any easy way to do this, without using JSON.parse or other JSON friendly methods? Old fashioned Javascript is what I'm looking for.

有没有简单的方法可以做到这一点,而不使用 JSON.parse 或其他 JSON 友好的方法?老式的 Javascript 是我正在寻找的。

回答by SLV

The most elegant way is:

最优雅的方式是:

let arrayToMap = [
  {'el' : 123},
  {'el' : 234},
  {'el' : 345}
];
let mappedArray = arrayToMap.map(item => item.el);

You can also do:

你也可以这样做:

let mappedArray = [
  {'el' : 123},
  {'el' : 234},
  {'el' : 345}
].map(item => item.el);

回答by Ravi Thapliyal

You can simply loop over the array of objects and only push()the values into a new one.

您可以简单地遍历对象数组,并且只push()将值循环到一个新的数组中。

var arrOfObjs = [
    { 'el' : 123 } ,
    { 'el' : 234 }, 
    { 'el' : 345 }
];

var arrOfVals = [];
for each( var obj in arrOfObjs ) {
    arrOfVals.push( obj.el );
}

for each( var val in arrOfVals ) {
    console.log( val ); // 123, 234, 345
}

回答by czl

 var rawArray = [
    {'el': 123},
    {'el': 234}, 
    {'el': 345}
 ]

 var myArray  = rawArray.map(item=>item.el);

回答by frulo

const _ = require( 'lodash' );
const mappedArray = _.map( arrayToMap, 'el' )