JavaScript对象将对象键移动到值阵列
如何将键传输到作为对象的值。 我想将产品 ID 级别的键移动到“id”值
我有一个像这样的数组:
const products = [
{
"2": {
"name": "Name of product with id 2",
"ean": "123123123",
"parameters": []
},
"3": {
"name": "Name of product with id 3",
"ean": "123123122",
"parameters": []
},
"5": {
"name": "Name of product with id 5",
"ean": "123123121",
"parameters": []
}
}
]
我期待这样:
[
{
"id": "2",
"name": "Name of product with id 2",
"ean": "123123123",
"parameters": []
},
{
"id": "3",
"name": "Name of product with id 3",
"ean": "123123122",
"parameters": []
},
{
"id": "5",
"name": "Name of product with id 5",
"ean": "123123121",
"parameters": []
}
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数组#映射
,在上面迭代,然后将id
添加到其他属性Array#flatMap
andObject#entries
, get list of id-object pairsArray#map
, iterate over the above and addid
to the other properties您只需使用与 array。 map()方法。
演示:
You can simply achieve that by using Object.keys() along with Array.map() method.
Demo :