如何对包含数组对象的Object进行字符串化?

时间:2018-06-05 12:10:07

标签: javascript reactjs query-string

如何将此对象操作为URL查询参数。查询参数的示例应为

advocates=7195&categories=25&checkbox-active=true&checkbox-close=undefined&checkbox-filed=true&checkbox-notFiled=undefined&cities=Delhi&cities=mumbai

5 个答案:

答案 0 :(得分:1)

以下是转换任何json的代码,无论它有多深入查询参数:

var o = {
  "stage": 50,
  "categories": [25, 23, 28],
  "advocates": [{
    "key": "7195",
    "label": "kallol saikia"
  }],
  "cities": [{
    "key": 390,
    "label": "Delhi"
  }, {
    "key": 6,
    "label": "Mumbai"
  }],
  "checkbox-filed": true,
  "checkbox-active": true
}

function getParams(key, value) {
  var queries = [];
  var newKey;

  if (Array.isArray(value)) {
    for (var i = 0; i < value.length; i++) {
      newKey = key + "[" + i + "]";
      queries = queries.concat(getParams(newKey, value[i]));
    }
  } else if (value && typeof value === 'object' && value.constructor === Object) {
    for (var prop in value) {
      if (value.hasOwnProperty(prop)) {
        newKey = key ? key + "[" + prop + "]" : prop;
        queries = queries.concat(getParams(newKey, value[prop]));
      }
    }
  } else {
    queries.push(key + "=" + value);
  }

  return queries;
}

var query = getParams("", o).join("&");
console.log(query);

我希望这能解决你的问题。

答案 1 :(得分:0)

  1. 您可以尝试使用Post请求
  2. 使用JSON.Parse()JSON.stringify()发送JSON字符串 将params数组转换为JSON String并将其作为单个查询参数发送。 解码查询字符串参数(即JSON字符串)
  3. 添加示例

    var jsonString = JSON.stringify({
        "stage": 50,
        "categories": [25, 23, 28],
        "advocates": [{
            "key": "7195",
            "label": "kallol saikia"
        }],
        "cities": [{
            "key": 390,
            "label": "Delhi"
        }, {
            "key": 6,
            "label": "Mumbai"
        }],
        "checkbox-filed": true,
        "checkbox-active": true
    });
    // Pass down the Encoded Json 
    var encodedJson = encodeURI(jsonString); 
    console.log(encodedJson);
    // Decode Json
    var decodedJson = decodeURI(encodedJson);
    var decodedObject = JSON.parse(decodedJson);
    console.log(decodedObject);
    
      

    <强>输出   &#34;%7B%22stage%22:50,%22categories%22:%5B25,23,28%5D,%22advocates%22:%5B%7B%22key%22:%227195 22%,%22label%22 :%22kallol%20saikia%22%7D%5D,%22cities%22:%5B%7B%22key%22:390,%22label%22:%22Delhi%22%7D,%7B%22key%22:6,% 22label%22:%22Mumbai%22%7D%5D,%22checkbox提交的%22:真,%22checkbox活性%22:真%7D&#34;

         

    对象{阶段:50,类别:数组[25,23,28],拥护者:数组[对象{键:&#34; 7195&#34;,标签:&#34; kallol saikia&#34; }],cities:Array [Object {key:390,label:&#34; Delhi&#34; },Object {key:6,label:&#34; Mumbai&#34; }],checkbox-filed:true,checkbox-active:true}

答案 2 :(得分:0)

也许:

var o = {
  'advocates': [{
    key: 1
  }],
  'checkbox-active': true
};

var query = Object.keys(o).map(function(i) {
  var val;
  if (Array.isArray(o[i])) {
    val = o[i][0].key;
  } else {
    val = o[i];
  }
  return i + '=' + val;
}).join('&');

console.log(query);

答案 3 :(得分:0)

以下是我刚才做的一个例子:https://jsfiddle.net/BrandonQDixon/surwf7gd

下面的脚本将遍历对象的键并将它们转换为GET样式参数,这就是您的请求的样子。我把它变成了一个函数,所以你可以直接在一个对象上调用它。

如果您的对象具有嵌套对象,这也将递归地工作,但是要理解如果嵌套对象具有一些相同的键(或者通常有重复项),它们都将被添加到字符串中。

/**
  * This will turn an object into a GET style parameter
  * This scans recursively if 2nd param is set to true, but "flattens" every property into one string, so this may cause some overriding
  * This will encode the keys and values if 3rd param is set to true
  */
function paramatize(obj,recursive = true,encode = true) {
  let str = "";

  let len = Object.keys(obj).length
  let i = 0;
  for (let key in obj) {

    i++;
    if (typeof obj[key] === 'object' && recursive) {
      str += paramatize(obj[key]);
    } else {
      let nKey = (encode)?encodeURIComponent(key):key;
      let nValue = (encode)?encodeURIComponent(obj[key]):obj[key];

      str += nKey+"="+nValue;
    }

    if (i < len) {
      str += "&";
    }
  }

  return str;
}

答案 4 :(得分:0)

此算法可行。请注意,如果更改对象结构,可能会破坏

希望这会有所帮助:&gt;

&#13;
&#13;
advocates=7195&
categories=25&
checkbox-active=true&
checkbox-close=undefined&
checkbox-filed=true&
checkbox-notFiled=undefined&
cities=Delhi&
cities=mumbai


`${key}${i>0?'&':''}${val[0]}=${val[1]}`, ""
&#13;
    'advocates':
     'checkbox-active':
     'checkbox-close':
     'checkbox-filed':
     'checkbox-notFiled':
      arrStr += key[0] + '=';
      arrStr += key[1][0].key +  '&';
&#13;
unknown attribute 'hashtag' for Job.
&#13;
&#13;
&#13;