首页 > 解决方案 > 是否可以重写此 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-homecontent.page-home.title

标签: javascriptjson

解决方案


为此,您需要更改数据的结构,您需要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;
} ,{} )

推荐阅读