在Javascript中将对象中的键作为函数参数传递

时间:2012-09-16 05:48:03

标签: javascript json object

我打算在Javascript中编写一个函数。它将通过传递密钥进行处理。

// generate by coffeescript

var get_key, obj;

obj = [
  { name: 'Ape', sales: 100, location: 'US' },
  { name: 'Bob', sales: 200, location: 'UK' },
  { name: 'Cat', sales: 120, location: 'Hell' }
];

// What I want to do: (of cause it is wrong)

get_key = function(obj, key) {
  var item, value_arr, _i, _len;
  value_arr = [];
  for (_i = 0, _len = obj.length; _i < _len; _i++) {
    item = obj[_i];
    value_arr.push(obj.key);
  }
  return value_arr; // return array containing all values of key in object
};

alert(get_key(obj, 'sales')); // expect return 100,200,120

问题是:如何传递“密钥”?

P.S。我甚至不知道在这件事上搜索任何关键词(英语不好)。所以我在StackOverflow和Google中找不到任何答案。请提供一些正确提问的提示。

非常感谢!!

3 个答案:

答案 0 :(得分:2)

var get_key, obj;

obj = [
  { name: 'Ape', sales: 100, location: 'US' },
  { name: 'Bob', sales: 200, location: 'UK' },
  { name: 'Cat', sales: 120, location: 'Hell' }
];

// What I want to do: (of cause it is wrong)

get_key = function(obj, key) {
  var item, value_arr, _i, _len;
  value_arr = [];
  for (_i = 0, _len = obj.length; _i < _len; _i++) {
    item = obj[_i];
    if (key in item){
        value_arr.push(item[key]);
    }
  }
  return value_arr; // return array containing all values of key in object
};

alert(get_key(obj, 'sales')); // expect return 100,200,120

item是包含您要查找的密钥的对象,因此将value_arr.push(obj.key);更改为value_arr.push(item[key]);,您必须使用[]表示法通过访问对象属性变量,还添加了一个检查,以便在添加到数组之前查看该项是否具有属性key

答案 1 :(得分:1)

function get_key(arr, key) {
    return arr.map(function(el) {
        return el[key];
    });
}

如果需要支持旧浏览器,则需要将map函数添加到Array(check here)。

答案 2 :(得分:1)

var obj = [
    {
    name: 'Ape',
    sales: 100,
    location: 'US'},
{
    name: 'Bob',
    sales: 200,
    location: 'UK'},
{
    name: 'Cat',
    sales: 120,
    location: 'Hell'}
];

get_key = function(obj, key) {
    var result = [];
    for (var i = 0; i < obj.length; i++) {
        /*
         *  Here, obj[i] gives the object e.g: 
         * { name: 'Ape', sales: 100, location: 'US' }...
         * 
         * and obj[i][key] give the value of corresponding key e.g:
         * 100, 200... (suppose for: sales) 
         */

        result.push(obj[i][key]);
    }
    return result;
};

alert(get_key(obj, 'sales').join(',')); ​

Working sample


在您的代码中

只需更改行

item = obj[_i];
value_arr.push(obj.key);// this line

 value_arr.push(item[key]);