I have an array of keys: var keys = ["key1","key2","key3"]
and an array of Objects:
var objArr= [
{"key0":1,"key1":2,"key2":3,"key3":4},
{"key0":5,"key1":6,"key2":7,"key3":8}
]
I want to be able to get the values from the array of objects based off the array of keys. For example, the output of this would be valueArr = [[2,3,4],[6,7,8]]
I've tried the following:
var result = objArr.map(function(a) {
for (var i=0;i<keys.length;i++){
return a[keys[i]];
};
})
but this returns [2,6] because its just returning the first value it gets to. I'm not sure how to fix it so any help is appreciated, thanks!
Push value
in array and return array
from 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);
Or using Array#map
inside 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);
don't return
too early , the loop only went through the first item :
var result = objArr.map(function(a) {
var resp = [];
for (var i=0;i<keys.length;i++){
resp.push(a[keys[i]]);
};
return resp;
})
As an alternative , you can use Object.values()
function, as suggested here . Example:
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]);
}
This is not supported by Internet Explorer, Opera or Safari at the moment though
You coud use nested Array#map
.
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);
ES6
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(a => keys.map(k => a[k])); console.log(result);
You need to push the values onto an array, return
will immediately break out of execution and return the value.
Try this:
var result = objArr.map(function(a) {
var res = [];
for (var i=0;i<keys.length;i++){
res.push(a[keys[i]]);
};
return res;
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.