-2

从这个问题继续:Getting first object from javascript litteral

是否可以仅从一组名称:值对中获取值?假设我们有一个对象列表,每个对象都有任意数量的值:

var items = [
    {name:"Foo", age:16, gender:"m"},
    {name:"Bar", age:17, gender:"f"},
    {name:"foo", age:16, gender:"m"},
    {name:"bar", age:18, gender:"m"},
    {name:"foobar", age:18, gender:"f"},
    {name:"barfoo", age:20, gender:"f"}
];

如何返回如下列表:

var items = [
    ["Foo", 16, "m"],
    ["Bar", 17, "f"],
    ["foo", 16, "m"],
    ["bar", 18, "m"],
    ["foobar", 18, "f"],
    ["barfoo", 20, "f"]
];

我已经尝试过了,但想知道是否有更好的方法。

Array.prototype.getValues = function () {
    if(typeof(this[0]) != typeof({}))
        throw "Array values are expected to be == typeof({})";
    var items = [];
    for (var i = 0; i < this.length; i++) {
        var r = [];
        for (var l in this[i]) {
            r.push(this[i][l]);
        }
        items.push(r);
    }
    return items; 
};
4

1 回答 1

4
var newitems=[];
//loop through each item in the original
for(var i =0; i<items.length; i++)
{
  newitems[i] = [];
  //loop over the properties in each element and push it to an array
  for(var prop in items[i]){
    newitems.push(items[i][prop]);
  }
}

或者:

var newitems = items.map(function(elem){
  var item = [];
  for(var prop in elem){
    item.push(elem[prop]);
  }
  return item;
})
于 2013-03-11T00:56:50.393 回答