简体   繁体   English

从javascript中的对象数组替换模板中的键

[英]Replace keys in a template from array of objects in javascript

I have an array like this. 我有这样的数组。

var arr = [
    {
        Id:1533248,
        Name:"HP",
        ParentId:33113319,
        ParentName:"Brand Name"
    },
    {
        Id:1533764,
        Name:"Samsung",
        ParentId:33113319,
        ParentName:"Brand Name"
    }    
]

And a template. 和模板。

var template = 'a_{ParentName}:{ParentId}_({Name}:{Id})*'

I am trying to generate a string from template. 我正在尝试从模板生成字符串。 All i have is the array of objects. 我所拥有的只是对象数组。 Also section inside () can be repeated and separated by pipe. 也可以重复()内的部分,并用管道分隔。

This is the desired output. 这是所需的输出。

var result = 'a_brand-name:33113319_hp:1533248|samsung:1533764|sony:1533438';

There could be many objects in array with same ParentId . 具有相同ParentId数组中可能有许多对象。 I am trying to use regular expression but failing. 我正在尝试使用正则表达式,但失败了。 I am no good at regular expressions. 我不擅长正则表达式。
Please help. 请帮忙。

You can use JS RegExp's along with replace to swap out the variables in your template. 您可以使用JS RegExp和replace来交换模板中的变量。 Additionally you can sanitize your strings into the desired format (based on what I see, replace white-space with a hyphen and convert the string to lower-case) with replace. 另外,您可以将字符串消毒为所需的格式(根据我所看到的格式,用连字符替换空格,并将字符串转换为小写字母)并替换为。 It sounds like you have more data than is displayed above, so you may need to keep multiple templates (ie one for each parent) stored in an object where the keys are the parentId. 听起来您的数据比上面显示的要多,因此您可能需要在一个键为parentId的对象中保留多个模板(每个父对象一个)。 Using that structure, you can iterate through the array, updating your template for each parentId pretty quickly. 使用该结构,您可以遍历数组,非常快地更新每个parentId的模板。

var arr = [
    {
        Id:1533248,
        Name:"HP",
        ParentId:33113319,
        ParentName:"Brand Name"
    },
    {
        Id:1533764,
        Name:"Samsung",
        ParentId:33113319,
        ParentName:"Brand Name"
    }    
];


var template = 'a_{ParentName}:{ParentId}_({Name}:{Id})*';
arr.forEach(function(obj, i) {
  Object.keys(obj).forEach(function(key) {
    var newKey;
        if (typeof(obj[key]) === 'string') {
      newKey = obj[key].replace(/ /g, '-').toLowerCase();
    } else {
      newKey = obj[key];
    }

    var regex = new RegExp("{" + key + "}");
    template = template.replace(regex, newKey);
  });
  if (template.indexOf('({Name}:{Id})') === -1 && i < arr.length - 1) {
    template = template.replace(/\*/, '|({Name}:{Id})*');
  } else if(i === arr.length - 1) {
    template = template.replace(/[\*\(\)]/g, '');
  }
});

https://jsfiddle.net/mw3dwau7/2/ https://jsfiddle.net/mw3dwau7/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM