【发布时间】:2018-04-03 07:40:19
【问题描述】:
我有模板,其中占位符指定如下。 (.event.id, .event.properties.file, ...)
瞧,我想用下面的event-object 的值替换模板中的占位符。
var templates = [
{
a:"1",
a2: {some:"other Obj"},
a3: ["or","array"],
b: ".event.id",
b2: "'.event.name' and more strings",
},
{
dontKnowKeys: "of where the .event will be in",
mightNotBeHere: "no placeholder here",
butHereAgain: ".event"
andSomeDeep: ".event.properties.file is Full"
}
];
var event = {
id: "1234-uuid-something",
name: "I Am an awesome Event",
properties: {
file: "/root/foo",
type: "error"
}
};
// First thought (pretty dirty, huh?)
JSON.parse(JSON.stringify(templates).replace(someMagicRegex, event))
// Second thought
templates = templates.map((tpl) => {
return _.values(tpl).replace('.event.([a-z]+)',event["$1"]);
};
但这不适用于properties.file 键。
此外,如果层次结构任意延长怎么办.event.properties.file.cwd.path
毕竟我想拥有以下对象:
var out = [
{
a:"1",
a2: {some:"other Obj"},
a3: ["or","array"],
b: "1234-uuid-something",
b2: "'I Am an awesome Event' and more strings",
},
{
dontKnowKeys: "of where the {\"id\":\"1234-uuid-something\",\"name\":\"I Am an awesome Event\",\"properties\":{\"file\":\"/root/foot\",\"type\":\"error\"}} will be in",
mightNotBeHere: "no placeholder here",
butHereAgain: "{\"id\":\"1234-uuid-something\",\"name\":\"I Am an awesome Event\",\"properties\":{\"file\":\"/root/foot\",\"type\":\"error\"}}"
andSomeDeep: "/root/foo is Full"
}
];
【问题讨论】:
标签: javascript templates object lodash