从Javascript中的对象数组仅返回某些属性 [英] Returning only certain properties from an array of objects in Javascript

查看:291
本文介绍了从Javascript中的对象数组仅返回某些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个这样的物体

var object = function(key,text)
{
    this.key = key;
    this.text = text;
}

并创建这些对象的数组

var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');

有没有办法我只能检索数组中所有对象的属性之一?例如:

var keyArray = objArray["key"]; 

上面的示例没有将set keyArray返回任何值,但是我希望将其设置为如下所示:

keyArray = [
    'key1',
    'key2',
    'key3']

有人知道一种无需迭代objArray并手动将每个key属性复制到key数组的方法吗?

解决方案

使用

如果您要经常这样做,可以编写一个抽象出地图的函数:

function pluck(array, key) {
  return array.map(function(item) { return item[key]; });
}

实际上,Underscore库具有一个称为 pluck 的内置函数. >

If I have an object such that

var object = function(key,text)
{
    this.key = key;
    this.text = text;
}

And create an array of these objects

var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');

is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:

var keyArray = objArray["key"]; 

The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:

keyArray = [
    'key1',
    'key2',
    'key3']

Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?

解决方案

This is easily done with the Array.prototype.map() function:

var keyArray = objArray.map(function(item) { return item["key"]; });

If you are going to do this often, you could write a function that abstracts away the map:

function pluck(array, key) {
  return array.map(function(item) { return item[key]; });
}

In fact, the Underscore library has a built-in function called pluck that does exactly that.

这篇关于从Javascript中的对象数组仅返回某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆