Closed danielecr closed 6 years ago
Would be better to use lodash.get
for this. That would also simplify the existing logic.
yes, adding a dependence, to a package that does just that relay on another library that does that too: you would better write a blog tips ;) Anyway I am not maintaining this fork because I really need a different features, but your package is a good starting point and using lodash is a good idea also. (OOC: I need "SELECT {result[0].property}" generate an array ["SELECT ?" , ['string value of result[0].property'] ] .. code is working but it is getting complex, if I will ever need to add something I will consider lodash, and I will publish it in a new repo)
I'm not exactly sure what you're saying, but I just meant that it would be better to use lodash.get
in this PR than to manually implement the logic.
I mean, use lodash.get for this too
return template.replace(regex, (_, key) => {
let ret = data;
for (const prop of key.split('.')) {
ret = ret ? ret[prop] : '';
}
return ret || '';
});
it becomes
return template.replace(regex, (_, key) => lodash.get(data, key, ''));
but you can write this:
TIP, use of lodash.get for template:
let template = "string with obj.prop";
let data = {obj: {prop: 1} }
const regex = /{(.*?)}/g;
return template.replace(regex, (_, key) => lodash.get(data, key, ''));
I found one line https://stackoverflow.com/a/53187393/250970 that implement the change
like pupa("{results[0].field1", {results:[{field1:"val",field2:"val"},{field1:"v",field2:"v2"}]});