javascript - 是否可以重写此 JSON 以通过其字段访问对象?- 给出的例子
问题描述
我有这个 JSON 文本。
content =
[
{
"location": "page-home",
"id": "block2",
"title": "Design",
"body": "<p>some content blah blah </p>",
"image": false
},
{
"location": "page-home",
"id": "block1",
"title": "Business",
"body": "more here woooo</p>",
"image": false
},
{
"location": "page-home",
"id": "welcome",
"title": "Welcome",
"body": "<p>blah blha blah on time and on budget.</p>\r\n",
"image": false
}
]
现在,如果我想获取带有 ID 标题的对象,我必须这样做。
content.filter(function(item){
return item.location == "page-home";
}
我想知道我是否可以解析我拥有的 JSON,以便我可以简单地做content.page-home
,content.page-home.title
解决方案
为此,您需要更改数据的结构,您需要object of objects
每个对象的键是唯一键,在这种情况下,我将使用id
您的对象的,但如果可以是任何东西:
content =
{
"block2":{
"location": "page-home",
"id": "block2",
"title": "Design",
"body": "<p>some content blah blah </p>",
"image": false
},
"block1": {
"location": "page-home",
"id": "block1",
"title": "Business",
"body": "more here woooo</p>",
"image": false
},
"welcome": {
"location": "page-home",
"id": "welcome",
"title": "Welcome",
"body": "<p>blah blha blah on time and on budget.</p>\r\n",
"image": false
}
}
在这个例子中,而不是访问你想要的方式,content.page-home.title
你应该这样做:
content.block1.title
编辑: 如果要将数据转换为对象对象,可以执行以下操作:
let obj = content.reduce( (acc, item) => {
// Here you are creating a new object with the id of the current item, and assigning the whole object to this
return acc[item.id] = acc;
} ,{} )
推荐阅读
- python - timeit.timeit 方法的装饰器?
- java - Camel Saga:跨两个 Web 服务协调一个 saga
- python - 字典迭代
- android - Titanium Android - 使用包名打开应用程序
- html - 如何在 div 中显示像网格一样的图像
- javascript - Ramda:提取 uniq 值的平面数组
- android - 无法在 Android Studio 中查看属性窗口
- node.js - 无服务器出站流量保护
- javascript - 使用 json-server 正确获取删除调用?
- php - 在 PHP 中使用 array_merge() 合并数组和整数?