user4266822
user4266822

Reputation:

How to separate an object with keys and values into two arrays

I have an object:

var myObj = {
  name: 'dri',
  age: '22',
  sex: 'female'
}

I need separate the keys and the values in two arrays.

var keys = [];
var values = [];

How can I do that?

Upvotes: 1

Views: 46

Answers (2)

HaveNoDisplayName
HaveNoDisplayName

Reputation: 8497

You can try this:-

var keys = [];
var values = [];
for (var prop in data) {
   keys.push(prop);
   values.push(data[prop]);
}

Upvotes: 2

Ehsan
Ehsan

Reputation: 4464

Try this:

var data = {"name": "dri", "age": 22, "sex": "female"};

var data1 = [],
    data2 = [];

for (var property in data) {

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

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

}

Upvotes: 0

Related Questions