已知对象,如何根据模板字符串分别渲染对象中数组每个元素?

已知一个对象

const data = {
    age: 1,
    person: [
        { name: "bdd", date: "44444" },
        { name: "b222dd", date: "666" }
    ]
} 

现在提供模板

const expression = "{{person.name}}###{{person.date}}"

应该如何编写函数能输出以下字符串?

bdd###444,b222dd#666
阅读 2k
2 个回答

person 是一个数组。


 var arr = {age:1,person:[{name:'bdd',date:'44444'},{name:'b222dd',date:'666'}]}
 var expression = '{{person[0].name}}###{{person[0].date}}'

const tpl = (str='', data={}, config={
  open: '{{',
  close: '}}'
})=>str.split(config.open).reduce((acc,cur)=>(([variate,...other] = cur.split(config.close)),acc+=(new Function('data',`return data?.${variate||'_'}||"";`)(data))+other),'');
console.log(tpl(expression,arr));

bdd###44444

https://segmentfault.com/q/10...

const data = {
    age: 1,
    person: [
        { name: "bdd", date: "444" },
        { name: "b22dd", date: "666" },
    ]
}
const expression = "{{person.name}}###{{person.date}}"

const tpl = (s, d) => {
    const mem = []
    let len, j = 0
    const t = s.replace(/\{\{(.+?)\}\}/g, (_, p) => {
        const v = p.trim().split(".").reduce((a, v) => {
            if (! a) return console.error(`{{${p}}} is null before "${v}"`)
            if (a instanceof Array) {
                const c = a.map(o => o[v])
                len = c.length
                return c
            }
            return a[v]
        }, d)
        mem[j] = v
        return `@@${j ++}@@`
    })
    console.log(mem)
    return Array.from({ length: len }, (_, i) => t.replace(/@@(\d+)@@/g, (_, j) =>  mem[j] instanceof Array ? mem[j][i] : mem[j]))
}
console.log(tpl(expression, data).join(","))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏