javascript - 将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"
}
感谢你们对我的帮助。
解决方案
您可以使用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);
推荐阅读
- r - 如何将CSV中的二进制矩阵用于r中的先验算法
- python - 转换为十进制日期和月份时,日期格式字符串无效
- python - 在多个 python 线程上运行 powershell
- android - 更新应用程序后 SQlite“没有这样的表”
- json - Angular 7检查JSON解析是否返回特定对象的正确方法
- php - mysqli_multi_query 是否与多次调用 mysqli_query 相同?
- python - Django Rest Framework 使用子序列化器在父序列化器中创建子对象
- vb.net - 有没有更好的方法在表单中显示 Excel 电子表格?
- javascript - 谷歌只映射一个 infoWindow
- css - 将掩码应用于CSS中的父元素,但没有结果