Separate key and value pairs into two arrays

2019-02-19 01:43发布

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.

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-19 02:04
data1=[];
data2=[]
for (x in data) {
   data1.push(x);
   data2.push(data[x]);
}
查看更多
▲ chillily
3楼-- · 2019-02-19 02:08

You can loop through the properties with a for in loop, and then just assign them to arrays as needed.

Make sure you check whether the key is a property of the object, and not of the prototype.

var data1 = [];
var data2 = [];

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    data1.push(key);
    data2.push(p[key]);
  }
}
查看更多
Fickle 薄情
4楼-- · 2019-02-19 02:17
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.

查看更多
相关推荐>>
5楼-- · 2019-02-19 02:23

This function will split the data object into a keys and a values array. It returns an object, containing both arrays.

function splitObj(data){
  var keys = [],
      vals = [];
  for (var l in data) {
   if (data.hasOwnProperty(l){
    keys.push(l);
    vals.push(data[l]];
   }
  }
  return {keys: keys,vals:vals};
}
查看更多
登录 后发表回答