Ranjith Varadan Ranjith Varadan - 16 days ago 5
Javascript Question

Split string using regex expression

I need to split a dynamic string. The string may look like the one below having Code, Name and EffectDate. or it may have only (Code and Name) or (Code and EffectDate) or (Name and EffectDate). You got the point right.

{"Code":{"value":"1"},"Name":{"value":"Entity1"},"EffectDate":{"value":"23/11/2016"}}


to

...
this.data[0].key ='Code'; \\something like this (desired result)
this.data[0].value = '1';
this.data[1].key = 'Name';
this.data[1].value = 'Entity1';
this.data[2].key = 'EffectDate';
this.data[2].value = '23/11/2016';


What i did in my code :

...
filters:string;
data:string[];
...
this.data = this.filters.split("\b(?:(?!value)\w)+[a-zA-Z0-9/]\b");
console.log(this.data);


I used this pattern \b(?:(?!value)\w)+[a-zA-Z0-9/]\b but still couldn't get the desired result. The this.filter always returns only one array with the same string. Any advice would be helpful. Thank you.

Update #1:

I'm using PrimeNg extension for datatable and i get event as a parameter. In that, event.filters returns me a list of filter objects. I cannot send the object to the service, it needs to be in the format to work with the service.

enter image description here

Answer

That looks like JSON. What's to stop you from just doing data = JSON.parse(content) and iterating over the key-values using keys(data) for keys and data[i]["value"] for values?

Try something like this:

var data = [];
for(var i in event.filters){
  data.push({"key": i, "value": event.filters[i].value});
}