【问题标题】:Transform array of keys and array of values into array of objects javascript将键数组和值数组转换为对象数组javascript
【发布时间】:2021-05-21 08:27:00
【问题描述】:

我的问题和这个很相似:Merge keys array and values array into an object in JavaScript

但是,我似乎没有为我的示例找到解决方案。如果我有这两个数组:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

如何将它们组合成一个对象数组,这将是预期的结果?

[
  {
    x: 0,
    y: 1,
    z: 2,
  },
  {
    x: 10,
    y: 20,
    z: 30,
  },
]

【问题讨论】:

  • 问题是什么?只需执行链接问题values.length 次 (values.reduce(<magic>)) 中的步骤
  • values.map(x => x.reduce((a,c,i) => (a[keys[i]] = c, a), {}) 将是我非常快速的尝试

标签: javascript arrays json javascript-objects


【解决方案1】:

您可以为此使用Array.prototype.map()Array.prototype.reduce()

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const res = values.map(arr => arr.reduce((acc, curr, index) => {
  acc[keys[index]] = curr

  return acc;
}, {x: null, y: null, z: null}));

console.log(res);

或者你也可以在没有reduce() 的情况下这样做:

const res = values.map(arr => ({
  [keys[0]]: arr[0],
  [keys[1]]: arr[1],
  [keys[2]]: arr[2]
}));

【讨论】:

  • (你可能想增加地图中的索引,否则它将是相同的键/值重复三次)
【解决方案2】:

循环遍历值数组并为每个数组创建一个对象,然后循环遍历这些数组中的值并将键数组用作键。

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = [];
values.forEach((v, i) => {
  output[i] = {}; // create objects for each of the value arrays
  v.forEach((w, j) => {
    output[i][keys[j]] = w; // use the correct keys with each of the values
  });
});

console.log(output);

正如 cmets 也指出的,这可以通过 Array.reduce 来完成:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = values.map(x => { // for each of the values arrays
  return x.reduce((a, c, i) => { // take its values
    a[keys[i]] = c // map them to an object property one by one
    return a; // put them together in the same object.
  }, {});
});

console.log(output);

【讨论】:

    【解决方案3】:

    const keys = ['x', 'y', 'z'];
    
    const values = [
      [0, 1, 2],
      [10, 20, 30],
    ];
    
    
    function toObject(keys, values) {
        let final = []
         for (let i = 0; i < values.length; i++){
             let result = {};
             for(let j=0;j<keys.length;j++){
                 result[keys[j]] = values[i][j];
                
             }
            final.push(result)
         }
        return final 
        console.log(final)
         
     }
     
     toObject(keys,values )

    会有用的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多