2017-06-16 48 views
1

我有一個像遍歷字符串獲取密鑰和使用正則表達式的關鍵值相匹配的Javascript

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

對於信息的字符串,是由kibana自動生成此字符串(我恢復它通過URL)。

我的問題是: 有任何解決方案,從這個字符串中提取鍵和值和一個數組中得到的結果還是這樣的對象:

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

感謝

回答

2

我想你」重新尋找這樣的事情:

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)

拆分通過,字符串,然後通過:分割以括號內識別對象的鍵和值

+0

謝謝你,它完美:d –

0

字符串轉,通過逗號,通過循環,由冒號分開並添加到對象分割。

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);

+0

謝謝你的答案。 ^^ –

1

同其他但也有一些ES6語法: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>

相關問題