OOPMichael
OOPMichael

Reputation: 50

convert JSON array of key value pairs to JSON Array of strings in Javascript

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.

Upvotes: 2

Views: 8067

Answers (5)

KMA
KMA

Reputation: 1

This should do it:

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

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

Upvotes: 0

Lockless
Lockless

Reputation: 497

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386786

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

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

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

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100381

Using ES2015 (ES6)

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

See

Upvotes: 4

Related Questions