首页 > 解决方案 > 将数组转换为对象类型

问题描述

我想将数组转换为对象到具有键值对的特定对象。

[
    {
        "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"
    },
}

标签: javascriptjqueryarraysobjectecmascript-6

解决方案


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)


推荐阅读