我需要使用具有特定对象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模板?
答案 0 :(得分:0)
您可以将数组转换为具有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);