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

问题描述

如果我有一个这样的对象

var object = function(key,text){this.key = 键;this.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 并手动将每个键属性复制到键数组的方法来执行此操作?

解决方案

这很容易通过 Array.prototype.map() 函数:

var keyArray = objArray.map(function(item) { return item["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 中的对象数组返回某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:26