2

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.

4
  • Does the order of the array elements matter? Is it OK if it's [["val2", "val1"], ["val1", "val2"]]? Commented Jan 6, 2017 at 20:57
  • yes it does but the accepted answer by @BrunoLM does preserve order. Commented Jan 6, 2017 at 22:15
  • No it doesn't, since the objects themselves don't preserve order. 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. Commented Jan 6, 2017 at 22:51

4 Answers 4

6

Using ES2015 (ES6)

const arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]
var newArr=arr.map(o => Object.values(o));

console.log(newArr);

See

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

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)
}

Comments

0

This should do it:

const arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}];

const newArr = arr.map(obj => Object.values(obj));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.