简单的插值计算

node v10.16.3
version: 1.0.0
endpointsharetweet
const _ = require('lodash'); function parseMenu(menus, data){ menus.forEach(function(menu){ if(menu.href&&(/({{[\w\.]+}})/g).test(menu.href)){ let interpolations = menu.href.match(/({{[\w\.]+}})/g); interpolations.forEach(function(interpolation){ let attrStr = interpolation.replace(/[{}]/g,''); let evaluated = _.get(data, attrStr); menu.href = menu.href.replace(interpolation, evaluated); }) } if(menu.children){ parseMenu(menu.children, data) } }) return menus; } let data={host:'localhost',para:{key:'js',limit:20,page:3}}; let menus=[ {name:'m1',href:'https://{{host}}/blog?key={{para.key}}&limit{{para.limit}}&page={{para.page}}'}, {name:'m2',children:[ {name:'m3',href:'https://{{host}}/blog?key={{para.key}}&limit{{para.limit}}&page={{para.page}}'}, {name:'m4',href:'https://{{host}}/blog?key={{para.key}}&limit{{para.limit}}&page={{para.page}}'} ]} ] let parsedMenu = parseMenu(menus, data); console.log('parsedMenu:',parsedMenu)
Loading…

no comments

    sign in to comment