如何从两个不同的数组创建对象数组?

huangapple go评论97阅读模式
英文:

how to create array of objects from 2 different array?

问题

我有两个长度不同且每个数组中的项目数量是动态的数组。我想要合并这两个数组,并将finalArray作为输出。我该如何做?

  1. const array1 = [7665, 7666];
  2. const array2 = [
  3. {
  4. "id": 1,
  5. "name": "user-1",
  6. },
  7. {
  8. "id": 2,
  9. "name": "user-2",
  10. },
  11. {
  12. "id": 3,
  13. "name": "user-3",
  14. },
  15. ];
  16. const finalArray = array2.map(item => {
  17. const obj = {};
  18. array1.forEach(num => {
  19. obj[num] = [];
  20. });
  21. obj["users"] = item["name"];
  22. return obj;
  23. });

这段代码将会生成你所期望的finalArray

英文:

I have 2 arrays with different lengths and the number of items in each array is dynamic. I want to merge these 2 arrays and have the finalArray as an output. How can I do that?
I want to add each item in array1 to all objects of array2 as key and an empty array as value.

  1. const array1 = [7665,7666]
  2. const array2 = [
  3. {
  4. "id": 1,
  5. "name": "user-1",
  6. },
  7. {
  8. "id": 2,
  9. "name": "user-2",
  10. },
  11. {
  12. "id": 3,
  13. "name": "user-3",
  14. },
  15. ]
  16. const finalArray = [
  17. {
  18. 7665: [],
  19. 7666: [],
  20. users: 'user-1',
  21. },
  22. {
  23. 7665: [],
  24. 7666: [],
  25. users: 'user-2',
  26. },
  27. {
  28. 7665: [],
  29. 7666: [],
  30. users: 'user-3',
  31. }
  32. ]

答案1

得分: 0

以下是翻译好的内容:

  1. const array1 = [7665, 7666];
  2. const array2 = [{
  3. "id": 1,
  4. "name": "user-1",
  5. },
  6. {
  7. "id": 2,
  8. "name": "user-2",
  9. },
  10. {
  11. "id": 3,
  12. "name": "user-3",
  13. },
  14. ];
  15. const result = array2.map(({ id, name }) => ({
  16. ...array1.reduce((acc, cur) => ({
  17. ...acc,
  18. [cur]: []
  19. }), {}),
  20. users: name
  21. }))
  22. console.log(result)
英文:

Here you go:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. const array1 = [7665, 7666];
  2. const array2 = [{
  3. &quot;id&quot;: 1,
  4. &quot;name&quot;: &quot;user-1&quot;,
  5. },
  6. {
  7. &quot;id&quot;: 2,
  8. &quot;name&quot;: &quot;user-2&quot;,
  9. },
  10. {
  11. &quot;id&quot;: 3,
  12. &quot;name&quot;: &quot;user-3&quot;,
  13. },
  14. ];
  15. const result = array2.map(({ id, name }) =&gt; ({
  16. ...array1.reduce((acc, cur) =&gt; ({
  17. ...acc,
  18. [cur]: []
  19. }), {}),
  20. users: name
  21. }))
  22. console.log(result)

<!-- end snippet -->

The map creates one object per user from array2. The reduce converts each number in array1 to a key on the final user object.

huangapple
  • 本文由 发表于 2023年7月4日 20:57:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定