I’m going to write a function in Javascript. It will process by passing a key.
// 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
Problem is: how to pass the ‘key’?
p.s. I even don’t know any keyword to search in this matter (bad English). So I can’t find any answer in StackOverflow and Google. Please give some tips to ask correctly.
Many thanks!!
itemis the object with the key you’re looking for so changevalue_arr.push(obj.key);tovalue_arr.push(item[key]);, you have to use[]notation to access an objects property via a variable, also added a check to see if the item has a propertykeybefore adding to the array.