javascript - 将数组转换为对象类型
问题描述
我想将数组转换为对象到具有键值对的特定对象。
[
{
"key": "out.of.stock",
"value": "out of stock"
},
{
"key": "buy.now",
"value": "BUY NOW"
},
{
"key": "notify.me",
"value": "You'll receive an email"
},
]
输出要求:
{
labels :{
"out.of.stock" : "out of stock",
"buy.now" : "BUY NOW",
"notify.me": "You'll receive an email"
}
}
我尝试使用 loadash (keyBy) 但输出如下:
{
"out.of.stock": {
"key": "out.of.stock",
"value": "out of stock"
},
"buy.now":{
"key": "buy.now",
"value": "BUY NOW"
},
"notify.me": {
"key": "notify.me",
"value": "You'll receive an email"
},
}
解决方案
const data = [
{
"key": "out.of.stock",
"value": "out of stock"
},
{
"key": "buy.now",
"value": "BUY NOW"
},
{
"key": "notify.me",
"value": "You'll receive an email"
},
]
const result = data.reduce((acc, next) => {
acc.labels[next.key] = next.value
return acc
}, { labels: {} })
console.log(result)
推荐阅读
- openstack - 如何检查是否有足够的资源来创建实例?
- python - 按时间拆分分组的熊猫数据帧
- r - 解析 R 中的字符串并将值与另一列进行比较
- hadoop - 无法执行 import-hive.sh
- graphql - Mirage 需要用于嵌套数据播种的数组
- jquery - jQuery在尝试单击任意位置时关闭模式
- javascript - 聚合框架在 mongodb 中无法正常工作
- python - Facebook 从 image_hash 获取 AdImage url
- python-3.x - 颜色 = Color.query.all()
- reactjs - Reactjs 挂钩中的 Starter 需要从 column.js 组件中调用单击事件 openModal() ,其中事件在 Table.js 中定义