我需要使用具有特定对象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);
添加回答
举报
0/150
提交
取消