如何使用jQuery将序列化的字符串转换为数组

时间:2018-07-12 18:25:22

标签: jquery arrays string serialization

我有这个字符串

foo = 'accordion-section[]=eat&accordion-section[]=pray&accordion-section[]=love'

如何在jquery中将其转换为array('eat', 'pray', 'love')

3 个答案:

答案 0 :(得分:0)

var foo = 'accordion-section[]=eat&accordion-section[]=pray&accordion-section[]=love';

//split the string by the & so you get key value pairs, and reduce them into a single object
var params = foo.split('&').reduce(function(results, keyValue){
  //split the key value pair by the =
  var [key, value] = keyValue.split('=');
  
  //if the key already exists, we need to convert the value to an array, and then push to the array
  if (results[key]) {
    if (typeof results[key] === 'string') {
      results[key] = [ results[key] ];
    }
    
    results[key].push(value);
  } else {
    //key did not exist, just set it as a string
    results[key] = value;
  }
  
  //return the results for the next iteration
  return results;
}, {});

//console.log the results
console.log(params);

答案 1 :(得分:0)

function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key] === "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key] === "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

foo = 'accordion-section[]=eat&accordion-section[]=pray&accordion-section[]=love';

// as an object
console.log(parse_query_string(foo))


// as an array
var fooArray = $.map(parse_query_string(foo), function(value, index) {
    return [value];
});
console.log(fooArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

它不是jQuery,但是您可以使用新的URLSearchParams api将值提取到新数组中。

注意:IE不支持。

const foo = 'accordion-section[]=eat&accordion-section[]=pray&accordion-section[]=love&anotherValue=5';

const searchParams = new URLSearchParams(foo);

const result = searchParams.getAll('accordion-section[]');

console.log(result);