Destructure an array of objects and create a new array with array keys as a new value in JavaScript

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

Destructure an array of objects and create a new array with array keys as a new value in JavaScript

问题

以下是您要翻译的内容:

分解和数组对象并在JavaScript中从数组键创建新的对象数组

现有的对象数组如下所示 -

```javascript
  [
    {
      "Semester One" : [
        {
          id:"1",
          name:"Name1",
        },
        {
          id:"2",
          name:"Name2",
        }
      ],
      "Semester Two" : [
        {
          id:"3",
          name:"Name3",
        },
        {
          id:"4",
          name:"Name4",
        }
      ]
    }
  ]

我想要实现的是这样的:

[
  {
    id:"1",
    name:"Name1",
    semester:"Semester One" // 数组键
  },
  {
    id:"2",
    name:"Name2",
    semester:"Semester One" // 数组键
  },
  {
    id:"3",
    name:"Name3",
    semester:"Semester Two" // 数组键
  },
  {
    id:"4",
    name:"Name4",
    semester:"Semester Two" // 数组键
  },
]

我能够成功创建具有值的对象数组,但我无法访问像"Semester One, Semester Two"这样的数组键。

到目前为止,我所做的是 -

 const arrObj = [];
    paperList.forEach((element) => {
      for (const key in element) {
        element[key].forEach((e, i) => {
          arrObj.push({
            ...e,
            semester: "", // 不知道如何获取这个值
            isChecked: "",
          });
        });
      }
    });
    console.log(arrObj);

<details>
<summary>英文:</summary>

Distructure and array of object and create a new array of object with a new value from the array keys in Javascript.

Existing Array of object is this -

[
{
"Semester One" : [
{
id:"1",
name:"Name1",
},
{
id:"2",
name:"Name2",
}
],
"Semester Two" : [
{
id:"3",
name:"Name3",
},
{
id:"4",
name:"Name4",
}
]
}
]


### what I want to achive, is this :

[
{
id:"1",
name:"Name1",
semester:"Semester One" // array key
},
{
id:"2",
name:"Name2",
semester:"Semester One" // array key
},
{
id:"3",
name:"Name3",
semester:"Semester Two" // array key
},
{
id:"4",
name:"Name4",
semester:"Semester Two" // array key
},
]


I am able to successfully create an array of objects with a value, but I can&#39;t access the array keys like &quot;Semester One, Semester Two&quot;

Here is what I have done so far -

const arrObj = [];
paperList.forEach((element) => {
for (const key in element) {
element[key].forEach((e, i) => {
arrObj.push({
...e,
semester: "", // don't know how to get this value
isChecked: "",
});
});
}
});
console.log(arrObj);



</details>


# 答案1
**得分**: 0

你可以像这样实现数组,使用 foreach 并将其推送到新数组中。

```js
var newArray = [];

originalArray.forEach((item) => {
  Object.keys(item).forEach((key) => {
    item[key].forEach((obj) => {
      newArray.push({
        id: obj.id,
        name: obj.name,
        semester: key,
      });
    });
  });
});
英文:

you can achieve the array like this, use a foreach and push to new array.


var newArray = [];

originalArray.forEach((item) =&gt; {
  Object.keys(item).forEach((key) =&gt; {
    item[key].forEach((obj) =&gt; {
      newArray.push({
        id: obj.id,
        name: obj.name,
        semester: key,
      });
    });
  });
});

答案2

得分: 0

Here is the translated content without the code:

另一个可以使用的解决方案(较短):

const arr = [
  {
    "第一学期": [
      {
        id: "1",
        name: "姓名1",
      },
      {
        id: "2",
        name: "姓名2",
      }
    ],
    "第二学期": [
      {
        id: "3",
        name: "姓名3",
      },
      {
        id: "4",
        name: "姓名4",
      }
    ]
  }
];

const result = arr.flatMap(sem => // 遍历每个元素
    Object.keys(sem).flatMap(semId => // 获取学期标识符
        sem[semId].map(y => // 在学期上映射
            ({id: y.id, name: y.name, semester: semId}) // 格式化输出
        )
    )
);
console.log(result);

请注意,这是您提供的代码的中文翻译部分。如果您需要进一步的帮助或有其他问题,请随时提出。

英文:

Another solution you can use (shorter) :

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

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

const arr = [
  {
      &quot;Semester One&quot; : [
        {
          id:&quot;1&quot;,
          name:&quot;Name1&quot;,
        },
        {
          id:&quot;2&quot;,
          name:&quot;Name2&quot;,
        }
      ],
      &quot;Semester Two&quot; : [
        {
          id:&quot;3&quot;,
          name:&quot;Name3&quot;,
        },
        {
          id:&quot;4&quot;,
          name:&quot;Name4&quot;,
        }
      ]
    }
  ];

const result = arr.flatMap(sem =&gt;                           // iterate through each elements
    Object.keys(sem).flatMap(semId =&gt;                   // get semesters identifier
        sem[semId].map(y =&gt;                             // map on semesters
            ({id: y.id, name: y.name, semester: semId}) // format the output
        )
    )
);
console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月24日 20:02:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76323311.html
匿名

发表评论

匿名网友

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

确定