javascript - 两个数组的对象到一个对象数组

标签 javascript

我有这样的数据:

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
}

我想把它转换成:

var newData = [
  {value1: "a", value2: 1},
  {value1: "b", value2: 2},
  {value1: "c", value2: 3}
]

如何使用 javascript 实现此目的?

最佳答案

使用Array#map生成数组的方法。

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
};

// iterate over the first property
var res = data.value1.map(function(v, i) {
  // generate the array object element
  return {
    value1: v,
    value2: data.value2[i]
  }
});

console.log(res);


更新 1:如果属性名称未知,那么您可以执行类似的操作。

var data = {
  value1: ["a", "b", "c"],
  value2: [1, 2, 3]
};

// get all property names
var keys = Object.keys(data);

// iterate over the first property name array
var res = data[keys[0]].map(function(v, i) {
  // generate the object by iterating over the keys array
  return keys.reduce(function(obj, k) {
    // define the object property
    obj[k] = data[k][i];
    // return the objet reference
    return obj;
    // set initial value as empty object
  }, {});
});

console.log(res);


更新 2:如果数组长度可以不同,那么您需要从集合中获取更大的数组。

var data = {
  value1: ["a", "b", "c", "d"],
  value2: [1, 2, 3],
  value3: [1, 2, 3, 5, 6, 7, 8]
};

// get all property names
var keys = Object.keys(data);

// iterate over the largest array
var res = data[
  // get the largest array holding key from the keys array  
  keys.reduce(function(k, k1) {
    return data[k1].length > data[k].length ? k1 : k;
  })
].map(function(v, i) {
  // generate the object by iterating over the keys array
  return keys.reduce(function(obj, k) {
    // check element exist in the array by comparing
    // the length and index
    if (data[k].length > i)
    // define the property if value exist in index
      obj[k] = data[k][i];
    // return the objet reference
    return obj;
    // set initial value as empty object
  }, {});
});

console.log(res);

关于javascript - 两个数组的对象到一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41500740/

相关文章:

javascript - 无法从 $.get 获得响应

javascript - 检查元素是否未显示 - WebDriverJS

php - 将类添加到指定元素

javascript - 根据先前捕获的组值进行检查

javascript - JQuery - mousedown、mouseup 并单击同一元素

javascript - NuxtJS 静态生成的 HTML 页面在调用/index.html 时不加载 Javascript

javascript - 如何使用采用接口(interface)实现类作为参数的方法编写 Flow 接口(interface)?

javascript - 如何从 for 循环中随机选择颜色和形状并将其显示在另一个 div 中?

c# - 如何从代码隐藏中获取 javascript 中设置的值?

javascript - 如何检测 URL 是否指向 SWF