用json数据填充html模板

我需要使用具有特定对象ID的Json数据填充html模板。


假设我的json数据位于名为mydata.json的文件中,如下所示:


[

    {

        "ID": "001",

        "title": "This is my title",

        "content": "This is my content"

    },

    {

        "ID": "002",

        "title": "This is my title",

        "content": "This is my content"

    },

    {

        "ID": "003",

        "title": "This is my title",

        "content": "This is my content"

    }

]

我如何才能加载该文件并仅用对象ID 002中的数据填充html模板?


慕盖茨4494581
浏览 152回答 1
1回答

萧十郎

您可以将数组转换为具有ID属性的对象:const contArr = [{    "ID": "001",    "title": "This is my title 1",    "content": "This is my content 1"  },  {    "ID": "002",    "title": "This is my title 2",    "content": "This is my content 2"  },  {    "ID": "003",    "title": "This is my title 3",    "content": "This is my content 3"  }];const contObj = contArr.reduce((o, c) => [o, o[c.ID] = c][0], {});console.log(contObj['002'].title);console.log(contObj['003'].content);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript