1

I have a string like

> var temp =
> "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green),"

For information, this string is generated automatically by kibana (I recover it through the url).

My question is : There is any solutions to extract keys and values from this string and get a result in a array or an object like this :

>  var result = { 
>                  "alias" : "!n",
>                  "apply" : "!t",
>                  "disabled" : "!f",
>                  "key": "stockInfo.raw",
>                  "negate": "!f",
>                  "value": "green",  
>               }

Thanks

3 Answers 3

2

I think you're searching something like this:

var meta = "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green),"

var result = {}

meta.substr(0, meta.length - 2).substr(5).split(',').forEach(function(item) {
  var split = item && item.split(':')
  if (split.length) {
    result[split[0]] = split[1];
  }
})

console.log(result)

Split the string by , character and then split by : to identify key and value of object

Sign up to request clarification or add additional context in comments.

Comments

1

same as other but with some es6 syntax :D

const result = document.getElementById("result");
const input = document.getElementById("input");

// string: data from url, return only the portion from the parenthesis
const extract_meta_values = string => {
 const EXTRACTOR = /^meta\(([^\)]+)\)/g;
 return EXTRACTOR.exec(string)[1];
}

// string: is a string of key:values separated by a comma
const meta_values_to_array_of_objects = string => string.split(',').map( tuple => {
  const [key, value] = tuple.split(':');
  return { [key]: value };
});

const meta_values = extract_meta_values(input.value);
const final = meta_values_to_array_of_objects(meta_values);

// print out
result.innerText = JSON.stringify(final, null, 2);
pre {
  display: block;
  border: 1px solid darkgray;
}
<p>
<input value="meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green)," id=input />
</p>

<pre id=result></pre>

Comments

0

Substring to within parenthesis, split by comma, loop through, split by colon and add to an object.

var temp = "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green)";
var t = {};
temp
  .substr(temp.indexOf("(") + 1, temp.indexOf(")") - temp.indexOf("(") - 1)
  .split(",")
  .forEach(function(a) {
    var b = a.split(":");
    t[b[0]] = b[1];
  });
console.log(t);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.