【问题标题】:How can I merge two arrays and make them array of objects in JavaScript如何合并两个数组并使它们成为 JavaScript 中的对象数组
【发布时间】:2020-10-21 11:47:13
【问题描述】:

我有一个简单的问题。我有两个数组 A 和 B,我想通过混合两个数组来返回对象数组。

例如:

let a = [ 1, 2 ]

let b = [ 3, 4 ]

预期结果

const C = [
   { 
      a: 1,
      b: 3 
   },
   { 
      a: 2,
      b: 4 
   }
]

我该怎么做?

我尝试循环 A 然后 B 并每次都分配,但它没有工作。

【问题讨论】:

  • “我尝试循环 A 然后 B 并每次都分配,但它没有工作。” - 你也错过了添加这部分 -> minimal reproducible example
  • 映射并从第二个数组中获取索引的值:const merged = a.map((value, index) => ({a: value, b: b[index]}))

标签: javascript arrays object ecmascript-6


【解决方案1】:

您可以在其中一个数组上使用数组映射方法并使用index 从第二个数组中检索元素

let a = [1, 2]

let b = [3, 4];


let c = a.map((item, index) => {
  return {
    a: item,
    b: b[index]
  }

});

console.log(c)

【讨论】:

  • 感谢兄弟,这是 tric
【解决方案2】:

这样的事情应该可以工作:

let a = [1, 2];
let b = [3, 4];

// From @brk. This transforms each element of a to an object containing a's value and b's value
let c = a.map((item, index) => {
  a: item,
  b: b[index]
});

// Another way. Iterates through each element 
for (let i = 0; i < a.length; i++) {
  c[i].a = a[i];
  c[i].b = b[i];
}

// Yet another. A combination of the first two.
for (let [index, item] of Object.entries(a)) {
  c[index] = {
    a: item,
    b: b[index]
  };
}

当然有更优雅的解决方案,但我现在回避了

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2011-11-08
    • 2017-05-27
    • 2020-02-20
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多