从对象数组中,将属性的值提取为数组

编程入门 行业动态 更新时间:2024-10-24 12:22:20
本文介绍了从对象数组中,将属性的值提取为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个JavaScript对象数组,结构如下:

I have JavaScript object array with the following structure:

objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];

我想提取一个包含key foo ,结果为 [1,3,5] 。

I want to extract an array containing the values of key foo, resulting in a value of [ 1, 3, 5 ].

我已经完成了这个用琐碎的方法,如下:

I have accomplished this with the trivial approach, as follows:

function getFields(input, field) { var output = []; for (var i=0; i < input.length ; ++i) output.push(input[i][field]); return output; } var result = getFields(objArray, "foo"); // returns [ 1, 3, 5 ]

是否有更优雅,更高效的方法可以完成?

Is there a more elegant and performant method to accomplish?

关于建议重复的说明,该问题询问如何将对象转换为一个数组,这个问题询问如何从对象数组中提取单个属性。

Note about suggested duplicate, that question asks how to convert an object to an array, this question asks how to extract single property from an array of objects.

推荐答案

这是实现它的一种较短方式:

Here is a shorter way of achieving it:

让结果= objArray.map(a => a.foo);

更多推荐

从对象数组中,将属性的值提取为数组

本文发布于:2023-10-27 03:29:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   组中   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!