Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate key and value pairs into two arrays

What would be the best way to go about separating the key and values into two different arrays so that this -

var data = {"A Key": 34, "Another Key": 16, "Last Key": 10};

Would become this -

data1 = ["A Key", "Another Key", "Last Key"];
data2 = [34, 16, 10];

Thanks.

like image 573
usertest Avatar asked Dec 21 '22 15:12

usertest


1 Answers

var data = {"A Key": 34, "Another Key": 16, "Last Key": 10};

var data1 = [],
    data2 = [];

for (var property in data) {

   if ( ! data.hasOwnProperty(property)) {
      continue;
   }

   data1.push(property);
   data2.push(data[property]);

}
  1. Set up two different blank arrays.
  2. Iterate through the enumerable properties of the object.
  3. If data does not have this property explicitly (i.e. not higher up the prototype chain), skip this iteration.
  4. Push the key and its value to their respective arrays.

jsFiddle.

like image 97
alex Avatar answered Dec 24 '22 04:12

alex