[英]How to Interpolate JSON Array having template variable with other JSON Object efficiently in JavaScript
template = [
{
title: "Student 1",
records: [
{ key: "Roll No", value: "${student1.rollNo}" },
{ key: "Class", value: "${student1.class} standard" },
],
},
{
title: "Student 2",
records: [
{ key: "Roll No", value: "${student2.rollNo}" },
{ key: "Class", value: "${student2.class} standard" },
]
}
];
replacers={
student1:{
rollNo:100,
class:10
},
student2:{
rollNo:101,
class:12
}
}
template=[
{
title: "Student 1",
records: [
{ key: "Roll No", value: "100" },
{ key: "Class", value: "10 standard" }
],
},
{
title: "Student 2",
records: [
{ key: "Roll No", value: "101" },
{ key: "Class", value: "12 standard" }
]
}
];
插值/映射后 JSON 數組將如上所示:(不使用任何第三方包)
模板=[ {標題:“學生1”,記錄:[ {鍵:“卷號”,值:“100”},{鍵:“班級”,值:“10標准”}],},{標題: “學生2”,記錄:[{鍵:“卷號”,值:“101”},{鍵:“班級”,值:“12標准”}]}];
我認為這會對你有所幫助:D
function render(index, item){ return { title: `Student ${index}`, records: [ { key: "Roll No", value: `${item.rollNo}` }, { key: "Class", value: `${item.class} standard` }, ], } } const data=[ { rollNo:100, class:10 }, { rollNo:101, class:12 } ] const res = data.map( (item, index) => render(index+1, item)) console.log(res)
我有我的問題的解決方案,有什么有效的方法可以得到相同的結果
title: "Student 1",
records: [{
key: "Roll No",
value: "${student1.rollNo}"
},
{
key: "Class",
value: "${student1.class} standard"
},
],
},
{
title: "Student 2",
records: [{
key: "Roll No",
value: "${student2.rollNo}"
},
{
key: "Class",
value: "${student2.class} standard"
},
]
}
];
const data = {
student1: {
rollNo: 100,
class: 10
},
student2: {
rollNo: 101,
class: 12
}
}
var templateString = JSON.stringify(template);
for (var key in data) {
for (var innerKey in data[key]) {
if (data[key].hasOwnProperty(innerKey)) {
var val = data[key][innerKey];
templateString = templateString.split('${' + key + '.' + innerKey + '}').join(val);
}
}
}
template=JSON.parse(templateString);
根據我的理解,您想根據模板中的標題動態綁定 object 值,而不是對值進行硬編碼。 如果是,這里是 go :
const template = [ { title: "Student 1", records: [ { key: "Roll No", value: "" }, { key: "Class", value: " standard" }, ], }, { title: "Student 2", records: [ { key: "Roll No", value: "" }, { key: "Class", value: " standard" }, ] } ]; const replacers = { student1:{ rollNo:100, class:10 }, student2:{ rollNo:101, class:12 } }; template.forEach(obj => { Object.keys(replacers).forEach(key => { if (key === obj.title.replace(' ', '').toLowerCase()) { const innerKeys = Object.keys(replacers[key]); obj.records.forEach((o, i) => { o.value = replacers[key][innerKeys[i]] + o.value }) } }) }); console.log(template);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.