【问题标题】:JS Replace Placeholder value in objectJS替换对象中的占位符值
【发布时间】: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


    【解决方案1】:

    为您尝试了解决方案。试试看

    注意:这仅适用于您当前具有简单数组和对象的模板结构。并且正则表达式在键选择后需要空间。根据你的需要改变它。

    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.properties.type.depth.key",
        andSomeDeep: ".event.properties.file is Full"
      }
    ];
    
    var event = {
      id: "1234-uuid-something",
      name: "I Am an awesome Event",
      properties: {
        file: "/root/foo",
        type: {depth:{key:"i am deep"}}
      }
    };
    
    
    // First thought (pretty dirty, huh?)
    //JSON.parse(JSON.stringify(templates).replace(someMagicRegex, event))
    
    // Second thought
    templates = templates.map((tpl) => {
      return handleObject(tpl);
    });
    
    function handleObject(obj) {
      for (let keyname in obj) {
        obj[keyname] = checkTypes(obj[keyname])
      }
      return obj;
    }
    
    // assume you have objects and arrays also
    function checkTypes(value) {
      if (typeof value === 'string') {
           return replaceVal(value);
      } else if (_.isArray(value)) {
        //assume array has only strings
         return value.map((d)=>replaceVal(d))
      } else if (_.isObject(value)) {
        return handleObject(value);
      }
    }
    
    
    function replaceVal(str) {
      //console.log(str);
      return str.replace(/.event.([^\s]+)/, (match,capture)=>_.get(event,capture))
    }
    
    console.log(templates);
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>

    【讨论】:

    • 好吧,差不多了。 .event 本身并没有被替换,但可以单独处理
    • 是的,我尝试了 .event 但它是完整的对象,您需要在对象内指向一些键
    • 你也可以使用深层对象键,比如上面的 ''.event.properties.type.depth.key"。它会起作用
    • 是的,这就是 _.get() 的魔力(喜欢它,我想我只是错过了那个!),无论如何,我会单独检查/\.event /并替换为 JSON .stringify(事件)。无论如何,我们应该将您的正则表达式中的. 更改为\.。这将修复 dontKnowKeys 的未定义替换。这样后面就可以搜索到我刚才提到的正则表达式了。
    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2013-04-08
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多