为了账号安全,请及时绑定邮箱和手机立即绑定

用json数据填充html模板

用json数据填充html模板

慕盖茨4494581 2021-05-07 13:36:03
我需要使用具有特定对象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模板?
查看完整描述

1 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

您可以将数组转换为具有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);


查看完整回答
反对 回复 2021-05-13
  • 1 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信