如何将多个数组转换为多个对象的一个​​数组?

时间:2017-12-05 16:39:54

标签: javascript arrays object

给出以下数组:

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

如何生成一个看起来像这样的新对象数组:

let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];

这是我到目前为止所得到的:

for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}

谢谢!

5 个答案:

答案 0 :(得分:3)

使用Array#map函数并获取索引,您将使用该索引从第二个和第三个数组中获取项目。如果第一个数组的项目多于其他项目,我也使用||

let x = ['a', 'b', 'c',' d'];
let y = ['e', 'f', 'g', 'h'];
let w = ['i', 'j', 'k', 'l'];

let mapped = x.map((item, index) => ({ x: item, y: y[index] || '', w: w[index] || '' }));

console.log(mapped);

答案 1 :(得分:1)

尝试

var z = x.map( (s,i) => ({ x : x[i], y : y[i], w : w[i] }) );

解释

  • 使用map
  • 迭代x
  • 对于x的每个索引,返回一个对象,其密钥为xyz,其值来自各自的索引

<强>演示

&#13;
&#13;
var x = ['a', 'b', 'c', 'd'];
var y = ['e', 'f', 'g', 'h'];
var w = ['i', 'j', 'k', 'l'];

var z = x.map((s, i) => ({
  x: x[i],
  y: y[i],
  w: w[i]
}));

console.log(z);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

let items = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" ];
for (let i = 0; i < items.length; i++)
  Object.defineProperty(window, items[i], {
    value: items[i],
    writable: false
  });
//The code above there is just to define the variables in your arrays.

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

let keys = [ "x", "y", "w" ]; //This array contains the name for accessing to your arrays.
let dimension = Math.max(...keys.map(function(array) {
  return eval(array).length;
}));
let z = new Array(dimension);
for (let i = 0; i < dimension; i++) {
  let obj = {};
  for (let ii = 0; ii < keys.length; ii++) {
    let key = keys[ii];
    obj[key] = eval(key)[i];
  }
  z[i] = obj;
}

console.log(JSON.stringify(z));

您还可以查看此fiddle

答案 3 :(得分:0)

您可以使用以下forEach

var result = [];
a.forEach((currenValue, index) => {
    result.push({x:x[index], y:b[index], w:c[index]});
});
console.log(result);

答案 4 :(得分:0)

您可以使用带有对象键的数组,并使用数组减少数组。

var x = ['a', 'b', 'c', 'd'],
    y = ['e', 'f', 'g', 'h'],
    w = ['i', 'j', 'k', 'l'],
    keys = ['x', 'y', 'w'],
    result = [x, y, w].reduce(function (r, a, i) {
        a.forEach(function (v, j) {
            r[j] = r[j] || {}
            r[j][keys[i]] = v;
        });
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }