javascript - 如何创建具有多个键和元素的单个对象?

标签 javascript arrays json object

我有一个包含 key 及其 array 元素的数组

当我将它从数组转换为对象时,我得到 index 0 和 1 但这里我需要的索引应该是 array1array2

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];


function convert(arr) {
  let obj = new Object();

  arr.forEach((value, key) => {
    obj = value;
  });
  return obj;
}
console.log(convert(input))

所以在调用这个函数之后我得到了以下输出

{
  "array2": [
     {
      "id": 1,
      "name": "Test 1"
     },
    {
      "id": 2,
      "name": "Test 2"
    }
  ]
}

但是这里我需要的输出应该是这样的

{
  "array1": [
    {
      "id": 1,
      "name": "Test 1"
    },
    {
      "id": 2,
      "name": "Test 2"
    }
  ],
  "array2": [
    {
      "id": 1,
      "name": "Test 1"
    },
    {
      "id": 2,
      "name": "Test 2"
    }
  ]
}

如果我在 convert 函数中使用定义数组并将其推送,那么我将得到 index 0 和 1。

我怎样才能在这里得到预期的结果。

最佳答案

Spreading (...) 是关键:

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];


function convert(arr) {
  return arr.reduce((acc, curr) => ({ ...acc, ...curr }), {});
}
console.log(convert(input))
.as-console-wrapper { max-height: 100% !important; top: auto; }

您也可以将它与 Object.assign 结合使用在数组本身上:

let input = [{
    "array1": [{
      "id": 1,
      "name": "Test 1"
    }, {
      "id": 2,
      "name": "Test 2"
    }]
  },
  {
    "array2": [{
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 2,
        "name": "Test 2"
      }
    ]
  }
];


function convert(arr) {
  return Object.assign(...arr);
}
console.log(convert(input))
.as-console-wrapper { max-height: 100% !important; top: auto; }

关于javascript - 如何创建具有多个键和元素的单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530475/

相关文章:

c - printf 中的段错误

php - 使用 PHP 访问另一个对象内的数组内的对象

javascript - 如何使用reactjs动态填充 Bootstrap 网格?

java - 这个 Lucene 查询有什么问题?

JavaScript 不显示

javascript - ie 访问对象时出现 "...is null or not an object"错误?

c - 使用指针传递结构数组时遇到问题

json - 如何获取 yason :encode-alist to return the encoded string instead of sending it to a stream?

javascript - 调用 async wait 时 undefined 不是一个函数

javascript - 当你的模板有空格/文本节点时,WebKit 会导致 DOM 插入变慢吗?