简体   繁体   English

如何将方括号对象键从 URL 位置转换为 Javascript 中的嵌套对象?

[英]How to convert square bracket object keys from URL location into nested object in Javascript?

With:和:

var obj = { "object[foo][bar][ya]": 100 };

How can I create:我如何创建:

var obj = { object: { foo: { bar: { ya: 100 }}}};

Manual approach手动方法

Split the given string with bracket, then iterate through the resultant tokens to make the nested object:用括号拆分给定的字符串,然后遍历结果标记以创建嵌套对象:

Given给定的

var obj = { "object[foo][bar][ya]": 100 };

Split them so we get拆分它们,我们得到

var tokens = Object.keys(obj)[0]
    .split('[')
    .map(function(s){return s.replace(']','')});
    // tokens = [ 'object', 'foo', 'bar', 'ya' ]

Then make the nested object, inside out然后制作嵌套对象,由内而外

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

Result结果

{"object":{"foo":{"bar":{"ya":100}}}} {"object":{"foo":{"bar":{"ya":100}}}}

Their is no native things in javascript fr parsing nested object in querystring.在 javascript fr 解析查询字符串中的嵌套对象时,它们不是本机的东西。

You can use http://medialize.github.io/URI.js/ which is pretty damn good at the job.您可以使用http://medialize.github.io/URI.js/ ,它非常擅长这项工作。

console.log(URI.parseQuery("?&foo=bar&&foo=bar&foo=baz&"));

If you don't want to import the full library, this is just the part for querystring parsing (full credit to https://github.com/medialize/URI.js ):如果您不想导入完整的库,这只是查询字符串解析的部分(完全归功于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;
  }
};

You could get the parts and build a new object.您可以获取零件并构建一个新对象。

 const obj = { "object[foo][bar][ya]": 100, "object[foo][baz]": 200, "object[foo][bar][bar]": 50, "xy": 30 }; let newObj = {}; for (const i in obj) { let a = i.match(/([^\\[\\]]+)(\\[[^\\[\\]]+[^\\]])*?/g), p = obj[i]; j = a.length; while (j--) { q = {}; q[a[j]] = p; p = q; } // merge object let 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]; } console.log(newObj);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Here's an es6 version.这是一个es6版本。 Caution: Hasn't been tested for edge cases.注意:尚未针对边缘情况进行测试。

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;
  }, {});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javascript中使用方括号表示法的嵌套对象 - Nested object using square bracket notation in javascript 使用连接键将深层嵌套对象转换为浅层对象的 Javascript 函数 - Javascript function to convert deeply nested object to shallow object with concatenated keys 如何将 javascript obj 转换为带有嵌套对象的 URL 参数? - How to convert javascript obj into URL parameters with nested object in it? 如何将对象键转换为嵌套对象 - How to convert object keys to nested objects JavaScript:如何通过解构从嵌套对象复制几个键 - JavaScript: How to copying a few keys from a nested object by destructuring 如何在javascript中将嵌套对象转换为对象数组? - How to convert nested object to array of object in javascript? JavaScript中对象定义末尾的方括号后缀是什么意思? - What does this square bracket suffix at the end of the object definition in JavaScript mean? 使用javascript方括号表示法重新排列对象中的值 - Using javascript square bracket notation to re-arrange values in object 如何获取javascript嵌套对象中最深层嵌套对象的键(路径) - How to get keys (path to) the deepest nested object in a javascript nested object 如何在javascript上使用动态键设置嵌套对象 - How to set nested object with dynamic keys on javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM