有了:如何將方括號中的對象鍵從URL位置轉換爲Javascript中的嵌套對象?
var obj = { "object[foo][bar][ya]": 100 };
如何創建:
var obj = { object: { foo: { bar: { ya: 100 }}}};
有了:如何將方括號中的對象鍵從URL位置轉換爲Javascript中的嵌套對象?
var obj = { "object[foo][bar][ya]": 100 };
如何創建:
var obj = { object: { foo: { bar: { ya: 100 }}}};
手冊方法
用括號拆分給定的字符串,然後迭代結果令牌以生成嵌套對象:
鑑於
var obj = { "object[foo][bar][ya]": 100 };
分裂他們,所以我們得到
var tokens = Object.keys(obj)[0]
.split('[')
.map(function(s){return s.replace(']','')});
// tokens = [ 'object', 'foo', 'bar', 'ya' ]
然後使嵌套的對象,而外
var result = {};
tokens.reverse().forEach(function(key){
if (Object.keys(result).length==0){
result[key] = obj[Object.keys(obj)[0]]; // inner-most key-value
}
else{
var temp = {};
temp[key] = result;
result = temp;
}
});
結果
{ 「對象」:{ 「富」:{ 「吧」:{ 「爾雅」:100}}}}
他們是沒有原生的東西在JavaScript解析FR嵌套對象查詢字符串。
你可以使用http://medialize.github.io/URI.js/這是非常好的工作。
console.log(URI.parseQuery("?&foo=bar&&foo=bar&foo=baz&"));
如果您不希望導入整個庫,這僅僅是查詢字符串解析(充分肯定https://github.com/medialize/URI.js)部分:
var URI = {
decodeQuery: function(string, escapeQuerySpace) {
string += '';
try {
return decodeURIComponent(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
} catch(e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
},
parseQuery: function(string, escapeQuerySpace) {
if (!string) {
return {};
}
// throw out the funky business - "?"[name"="value"&"]+
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
if (!string) {
return {};
}
var items = {};
var splits = string.split('&');
var length = splits.length;
var v, name, value;
for (var i = 0; i < length; i++) {
v = splits[i].split('=');
name = URI.decodeQuery(v.shift(), escapeQuerySpace);
// no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
if (Object.prototype.hasOwnProperty.call(items, name)) {
if (typeof items[name] === 'string') {
items[name] = [items[name]];
}
items[name].push(value);
} else {
items[name] = value;
}
}
return items;
}
};
var obj = {
"object[foo][bar][ya]": 100,
"object[foo][baz]": 200,
"object[foo][bar][bar]": 50,
"xy": 30
};
var newObj = {}, a, i, j, k, o, p, q;
for (i in obj) {
a = i.match(/([^\[\]]+)(\[[^\[\]]+[^\]])*?/g);
p = obj[i];
j = a.length;
while (j--) {
q = {};
q[a[j]] = p;
p = q;
}
// merge object
k = Object.keys(p)[0];
o = newObj;
while (k in o) {
p = p[k];
o = o[k];
k = Object.keys(p)[0];
}
o[k] = p[k];
}
document.write('<pre>' + JSON.stringify(newObj, null, 4) + '</pre><br>');
這裏是一個ES6版本。小心:尚未經過邊緣案例的測試。
const keyPattern = /^(\w+)\[(\w+)\](.*)$/;
export function decodeParams(params) {
return Object.keys(params).reduce((result, key) => {
let match = key.match(keyPattern);
if (match && match.length >= 3) {
let [key, nextKey, rest = ''] = match.slice(1);
result[key] = Object.assign(
{},
result[key],
decodeParams({ [nextKey + rest]: params[key] })
);
} else {
result[key] = params[key];
}
return result;
}, {});
}
這不是一個非常強大的解決方案,但做起來+1 – Cyrbil
@cyrbil任何建議表示讚賞的漂亮聰明的方式:)我總是希望聽到別人怎麼想。 –