set poperty of nested object

2016-12-15  本文已影响8人  last_edc

2016-10-06

set poperty of nested object

1.

obj = {};  // global object
function set(path, value) {
var schema = obj;  // a moving reference to internal objects within obj
var pList = path.split('.');
var len = pList.length;
for(var i = 0; i < len-1; i++) {
    var elem = pList[i];
    if( !schema[elem] ) schema[elem] = {}
    schema = schema[elem];
}
schema[pList[len-1]] = value; 
}
set('mongo.db.user', 'root');

2.

function convertQueryToMap(query) {
var obj = {};
query.split('&').map(function(params) {
var parts = params.split('=');
if (!parts[1]) return {};
parts[0].split('.').reduce(function(cur, next, i, arr) {
  if (!cur[next]) cur[next] = {};
  if (i === arr.length - 1) cur[next] = decodeURIComponent(parts[1]);
  return cur[next];
}, obj);
});
return obj;
}

3.

`decodeURIComponent()' 对URL解码

上一篇 下一篇

猜你喜欢

热点阅读