so i have a JSON Object [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]
and i essentially need to remove the keys so the output looks like [["val1","val2"],["val1","val2"]]
in Javascript.
short of iterating through the array and then iterating through all the properties and mapping to a new JSON object is there any way i can remove the keys from the object, and turn the values in to a list in an array?
please no string splicing/ regex.
Thanks.
so i have a JSON Object [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]
and i essentially need to remove the keys so the output looks like [["val1","val2"],["val1","val2"]]
in Javascript.
short of iterating through the array and then iterating through all the properties and mapping to a new JSON object is there any way i can remove the keys from the object, and turn the values in to a list in an array?
please no string splicing/ regex.
Thanks.
Share Improve this question asked Jan 6, 2017 at 20:28 OOPMichaelOOPMichael 502 silver badges8 bronze badges 4-
Does the order of the array elements matter? Is it OK if it's
[["val2", "val1"], ["val1", "val2"]]
? – Barmar Commented Jan 6, 2017 at 20:57 - yes it does but the accepted answer by @BrunoLM does preserve order. – OOPMichael Commented Jan 6, 2017 at 22:15
- No it doesn't, since the objects themselves don't preserve order. – Barmar Commented Jan 6, 2017 at 22:42
- ahhh you are correct, thanks!@ i didn't notice it, b/c the first few arrays contained the same keyed data. – OOPMichael Commented Jan 6, 2017 at 22:51
5 Answers
Reset to default 5Using ES2015 (ES6)
const arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]
arr.map(o => Object.values(o));
See
- Array.map
- Object.values
If you still need old browser support--pre ES6
var arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}];
arr = arr.map(function(o){
var a = [];
for(var i in o){
a.push(o[i])
}
return a;
});
console.log(arr);
Plain ES5 with Array#map
var array = [{ key1: "val1", key2: "val2" },{ key1: "val1", key2: "val2" }],
mapped = array.map(function (o) {
return Object.keys(o).map(function (k) {
return o[k];
});
});
console.log(mapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You need to loop over the object and make new arrays.
for (var i = 0; i < yourobject.length; i++) {
var myArray = [];
for (var key in yourobject) {
myArray.push(yourobject[key]
}
console.log(myArray)
}
This should do it:
const arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}];
const newArr = arr.map(obj => Object.values(obj));