首页 > 解决方案 > 将json对象值变成javascript中的key和value

问题描述

我有一个如下的json格式。我很困惑,我们可以将第一个值作为键,将第二个值作为键的内容吗?

[
  {
      "configSlug": "receiptStoreName",
      "configContent": "The Store Name"
  },
  {
      "configSlug": "receiptStoreAddress",
      "configContent": "Cattle Street"
  },
  {
      "configSlug": "receiptStorePhone",
      "configContent": "01 123234"
  },
  {
      "configSlug": "receiptStoreFoot1",
      "configContent": "Thanks For Visiting"
  }
]

预期结果:

{
    "receiptStoreName": "The Store Name",
    "receiptStoreAddress": "Cattle Street",
    "receiptStorePhone": "01 123234",
    "receiptStoreFoot1": "Thanks For Visiting"      
}

感谢你们对我的帮助。

标签: javascriptjqueryarraysjsonobject

解决方案


您可以使用Object.fromEntries()

const obj = [
  {
      "configSlug": "receiptStoreName",
      "configContent": "The Store Name"
  },
  {
      "configSlug": "receiptStoreAddress",
      "configContent": "Cattle Street"
  },
  {
      "configSlug": "receiptStorePhone",
      "configContent": "01 123234"
  },
  {
      "configSlug": "receiptStoreFoot1",
      "configContent": "Thanks For Visiting"
  }
];

const result = Object.fromEntries(obj.map(entry => [entry.configSlug, entry.configContent]));

console.log(result);

或者你可以使用一个简单的循环:

const obj = [
  {
      "configSlug": "receiptStoreName",
      "configContent": "The Store Name"
  },
  {
      "configSlug": "receiptStoreAddress",
      "configContent": "Cattle Street"
  },
  {
      "configSlug": "receiptStorePhone",
      "configContent": "01 123234"
  },
  {
      "configSlug": "receiptStoreFoot1",
      "configContent": "Thanks For Visiting"
  }
];

const result = {};
for (const entry of obj) {
  result[entry.configSlug] = entry.configContent;
}

console.log(result);


推荐阅读