简体   繁体   English

将键和值对分成两个数组

[英]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. 谢谢。

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 (ie not higher up the prototype chain), skip this iteration. 如果data没有显式地具有此属性(即不高于原型链),请跳过此迭代。
  4. Push the key and its value to their respective arrays. 将键及其值推送到各自的数组。

jsFiddle . jsFiddle

This function will split the data object into a keys and a values array. 此函数将data对象拆分为键和值数组。 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};
}
data1=[];
data2=[]
for (x in data) {
   data1.push(x);
   data2.push(data[x]);
}

You can loop through the properties with a for in loop, and then just assign them to arrays as needed. 您可以使用for in循环遍历属性,然后根据需要将它们分配给数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM