如何在JavaScript中将嵌套对象转换为键值对
我想通过编程
问题
attributes: {
allow: [ '0' ],
create: [ '0' ],
all: [ '0' ],
rfid: [ '0' ],
}
我想要的是
attributes: {
allow:'0',
create: '0',
all:'0',
rfid: '0',
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
功能方法:
您可以使用
object.entries
转动对象{a:1, B:2}
进入数组数组(包含键和值对)[['a',1],['b',2]]
。然后,您可以使用 在每个操作上应用一个操作,并将数组的每个元素映射到操作的返回值。在我们的情况下,实际上我们将拥有[['lever',['0']],...]
之类的东西,并希望将其映射到[['['['['['允许','0'],...
。然后,在最后,我们使用object.fromentries
取回对象。映射操作可以简单地
([K,[V]])=> [k,v]
。使用破坏性,我们获得了一种表达方式来提取所需的价值并返回它。现在,由于整个过程似乎都在另一个具有
属性
为键的对象内部(而且我不知道是否可以使用其他键),所以我们将带有属性的另一个此类对象< /code>更换并保留了其他键:
命令方法:
此方法更简单,但会突变您的对象。您可以在
属性
对象中的键上循环,并用自己的第一个数组元素替换每个值,如下所示:Functional approach:
You can use
Object.entries
to turn an object{ a: 1, b: 2 }
into an array of arrays (containing pairs of keys and values)[['a', 1], ['b', 2]]
. You can then useArray#map
to apply an operation on each and mapping each element of the array to the return value of the operation. In our case, we'll actually have something like[['allow', ['0']], ...]
at that point and want to map it to[['allow', '0'], ...]
. Then at the end, we undo the first operation usingObject.fromEntries
to get an object back.The mapping operation can be simply
([k, [v]]) => [k, v]
. Using destructuring, we get an expressive way of extracting the value that we need and returning it.Now since the whole thing seems to be inside another object with
attributes
as key (and I don't know if there can be other keys), we'll return another such object withattributes
replaced and the other keys preserved:Imperative approach:
This approach is simpler, but will mutate your object. You can loop over the keys in the
attributes
object and replace each value with its own first array element, as follows: