javascript对象从键数组中获取值数组

时间:2016-07-28 19:56:49

标签: javascript key

我有一组键:var keys = ["key1","key2","key3"]和一个对象数组:

var objArr= [
    {"key0":1,"key1":2,"key2":3,"key3":4},
    {"key0":5,"key1":6,"key2":7,"key3":8}
]

我希望能够根据键数组从对象数组中获取值。例如,输出结果为valueArr = [[2,3,4],[6,7,8]]

我尝试过以下方法:

var result = objArr.map(function(a) {
    for (var i=0;i<keys.length;i++){
        return a[keys[i]];
    };
})

但是这会返回[2,6],因为它只返回它获得的第一个值。我不确定如何修复它,所以感谢任何帮助,谢谢!

5 个答案:

答案 0 :(得分:2)

在数组中推送value并从array

返回Array#map

var keys = ["key1", "key2", "key3"];
var objArr = [{
  "key0": 1,
  "key1": 2,
  "key2": 3,
  "key3": 4
}, {
  "key0": 5,
  "key1": 6,
  "key2": 7,
  "key3": 8
}];

var result = objArr.map(function(a) {
  var arr = [];
  for (var i = 0; i < keys.length; i++) {
    arr.push(a[keys[i]]);
  };
  return arr;
});
console.log(result);

或在Array#map

中使用Array#map

var keys = ["key1", "key2", "key3"];
var objArr = [{
  "key0": 1,
  "key1": 2,
  "key2": 3,
  "key3": 4
}, {
  "key0": 5,
  "key1": 6,
  "key2": 7,
  "key3": 8
}];

var result = objArr.map(function(a) {
  return keys.map(function(key) {
    return a[key];
  });
});
console.log(result);

答案 1 :(得分:1)

不要return太早,循环只通过第一项:

var result = objArr.map(function(a) {
    var resp = [];
    for (var i=0;i<keys.length;i++){
        resp.push(a[keys[i]]);            
    };
    return resp;
})

答案 2 :(得分:1)

作为 替代 ,您可以使用Object.values()功能,如建议的here。例如:

var objArr= [
    {"key0":1,"key1":2,"key2":3,"key3":4},
    {"key0":5,"key1":6,"key2":7,"key3":8}
];

for(var i in objArr){
    objArr[i] = Object.values(objArr[i]);
}

目前,Internet Explorer,Opera或Safari不支持此功能

答案 3 :(得分:1)

您可以使用嵌套的Array#map

&#13;
&#13;
LICENSE
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
var keys = ["key1", "key2", "key3"],
    objArr = [{ "key0": 1, "key1": 2, "key2": 3, "key3": 4 }, { "key0": 5, "key1": 6, "key2": 7, "key3": 8 }],
    result = objArr.map(function (a) {
        return keys.map(function (k) {
            return a[k];
        });
    });

console.log(result);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您需要将值推送到数组,return将立即中断执行并返回值。

试试这个:

var result = objArr.map(function(a) {
    var res = [];
    for (var i=0;i<keys.length;i++){
        res.push(a[keys[i]]);
    };
    return res;
})