javascript - JS : How to combine Object from two different arrays into one Array/Object

标签 javascript arrays vuejs2 array-push array-reduce

如果有两个数组(内容和 ids),我需要将它们组合成一个数组(组合)。

第一个数组:

let content = [
  { "Name": "Max Mustermann" },
  { "Name": "Berta Beispiel" },
  { "Name": "Zacharias Zufall" }
]

第二个数组:

let ids = [
  "12345678-1", 
  "12345678-2", 
  "12345678-3"
]

组合起来应该像这样:

let combined = [
  {
    "Name": "Max Mustermann",
    "id": "12345678-1"
  },
    {
    "Name": "Berta Beispiel",
    "id": "12345678-2"
  },
    {
    "Name": "Zacharias Zufall",
    "id": "12345678-3"
  }
]

我尝试了推送、减少、映射等不同的方法...但没有任何效果::(

最佳答案

它应该有效:

let content = [
  { "Name": "Max Mustermann" },
  { "Name": "Berta Beispiel" },
  { "Name": "Zacharias Zufall" }
]
let ids = [
  "12345678-1", 
  "12345678-2", 
  "12345678-3"
]
let combined = content.map((cnt, index) => {
  let idPart = {
    id: ids[index],
  };
  return {...cnt, ...idPart};
});
// Short version:
/*
let combined = content.map((c, i) => ({id: ids[i], ...c}));
*/

关于javascript - JS : How to combine Object from two different arrays into one Array/Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59183645/

相关文章:

unit-testing - vuejs中的单元测试

javascript - 有没有办法明确测试设备是否支持双击?

python - 无法 reshape 包含 PNG 图像的 numpy 数组

java - 生成与二维数组中最后一组数字仅相差 1 的数字组

java - Apache Spark - 无法理解 scala 示例

javascript - 无法从组件方法访问数据

php - 如何通过 HP 或平板电脑拍摄照片并使用 PHP 自动上传?

javascript - move_uploaded_file - 图像的文件名?

javascript - 对象内部引用声明

javascript - vue Js从对象绑定(bind)到数组