将对象父键附加到孩子
我有以下对象:
{
"groupA": [
{data: 'foo'},
{data: 'bar'}
],
"groupB": [
{data: 'hi'},
{data: 'mom'}
]
}
我想将父对象键添加到其所有数组项目中:
{
"groupA": [
{data: 'foo', set: 'groupA'},
{data: 'bar', set: 'groupA'}
],
"groupB": [
{data: 'hi', set: 'groupB'},
{data: 'mom', set: 'groupB'}
]
}
如何实现?
I have the following object given:
{
"groupA": [
{data: 'foo'},
{data: 'bar'}
],
"groupB": [
{data: 'hi'},
{data: 'mom'}
]
}
I would like to append the parent object keys to all its array items like so:
{
"groupA": [
{data: 'foo', set: 'groupA'},
{data: 'bar', set: 'groupA'}
],
"groupB": [
{data: 'hi', set: 'groupB'},
{data: 'mom', set: 'groupB'}
]
}
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个不变的版本,它可以使用
object.fromentries
Object.entries
和map
为您提供新对象。This is a immutable version that give you a new object using
Object.fromEntries
Object.entries
andmap
您可以循环并设置每个项目
You can loop and set each item
您可以通过在对象上循环并映射数组来做到这一点,例如:
You can do it simply by looping over the object and mapping the arrays, like this:
您也可以在中使用
You can use
for...in
as well您可以尝试
object.keys(arr)
获取所有密钥名称:============
[update] 在之后创建 之前:
You can try
Object.keys(arr)
to get all key name:==========
[UPDATE] Create
after
without changedbefore
: