将json对象值变成javascript中的键和值[关闭]
Posted
技术标签:
【中文标题】将json对象值变成javascript中的键和值[关闭]【英文标题】:Turn json object value become a key and value in javascript [closed] 【发布时间】:2021-04-12 01:13:59 【问题描述】:我有一个如下的 json 格式。我很困惑,能不能把第一个值作为key,第二个值作为key的内容?
[
"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"
谢谢你帮助我。
【问题讨论】:
请发布您自己编写的代码以尝试解决问题,以便我们帮助您调试它。请记住,SO 是为了帮助您解决代码中的问题,而不是为您编写代码。如果您在解决此问题时需要帮助,请研究map()
方法。
寻求帮助。考虑使用reduce方法
【参考方案1】:
你可以使用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);
【讨论】:
【参考方案2】:你可以使用Array.prototype.reduce()
,像这样:
const data = [
"configSlug": "receiptStoreName",
"configContent": "The Store Name"
,
"configSlug": "receiptStoreAddress",
"configContent": "Cattle Street"
,
"configSlug": "receiptStorePhone",
"configContent": "01 123234"
,
"configSlug": "receiptStoreFoot1",
"configContent": "Thanks For Visiting"
];
const result = data.reduce((r, e) =>
r[e.configSlug] = e.configContent;
return r;
, );
console.log(result);
它给出了输出:
receiptStoreName: "The Store Name",
receiptStoreAddress: "Cattle Street",
receiptStorePhone: "01 123234",
receiptStoreFoot1: "Thanks For Visiting"
【讨论】:
【参考方案3】:data.reduce((obj, item) => obj[item.configSlug] = item.configContent; return obj; , );
【讨论】:
以上是关于将json对象值变成javascript中的键和值[关闭]的主要内容,如果未能解决你的问题,请参考以下文章