JavaScript - 将字符串参数转换为数组

时间:2014-06-26 07:03:01

标签: javascript

我有一个这样的字符串:

var str = 'My_Type_1=SSD&My_Value_1=16GB&My_Category_1=Disk Capacity&My_Type_2=Sony
&My_Value_2=PS4&My_Category_2=Console&My_rowOrder=2,1';

The string mostly has 3 parts except the last key:
Part 1 -> My - is a Common Prefix
Part 2 -> Type or Value or Category and it can keep changing
Part 3 -> It's a numeric value binding Part 1, Part 2 and Part 3 like Spreadsheet row.

始终调用最后一个键 My_rowOrder,它是逗号分隔的值。它指定了如何构造输出数组。

在上面的例子中,2,1表示键值对 My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console应该是输出数组中的第一个。

使用JavaScript,我想解析字符串并从中创建一个数组,以便输出为:

Array
(
    [ 0 ] => Array
        (
            [Type] => Sony
            [Value] => PS4
            [Category] => Console
            [Row] => 2
        )

    [ 1 ] => Array
        (
            [Type] => SSD
            [Value] => 16GB
            [Category] => Disk Capacity
            [Row] => 1
        )  
)

我该怎么做?我部分能够这样做:

function StringToArray(string) {
          var request = {};
          var pairs = string.split('&');
          for (var i = 0; i < pairs.length-1; i++) {
            var pair = pairs[i].split('=');
            request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
          }
          //I think I am in the right track, but need assistance
    }

3 个答案:

答案 0 :(得分:1)

您的示例输出使用了JavaScript没有的关联数组,但您可以使用对象数组。

此示例按rowOrder参数指定的顺序输出对象数组。它修剪前缀(由prefix定义),并修剪键末尾的行号。

这也适用于任何顺序的参数 - 例如你可以混合它们,它会根据需要进行解析,rowOrder参数可以出现在字符串中的任何地方(不必在最后)。

<强> Demo

function StringToArray(string) {
    var prefix = 'My_'; // set the prefix
    var output = [], request = [];
    var pairs = string.split('&');
    var order;
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');

        if (pair[0].replace(prefix, '') == 'rowOrder') {
            order = pair[1];
        } else {
            var key = decodeURIComponent(pair[0]);
            var pos = key.lastIndexOf('_');
            var trimmedKey = key.substring(0, pos).replace(prefix, '');
            var row = key.substring(pos + 1);
            var value = decodeURIComponent(pair[1]);
            var found = false;

            for (var j = 0; j < output.length; j++) {
                if (output[j].Row == row) {
                    output[j][trimmedKey] = value;
                    found = true;
                }
            }

            if (!found) {
                var obj = { 'Row': row };
                obj[trimmedKey] = value;
                output.push(obj);
            }
        }
    }
    // do the ordering based on the rowOrder parameter
    var orderList = order.split(",");
    for(var k=0; k<orderList.length; k++){
        for(var l=0; l<output.length; l++){
            if(output[l].Row == orderList[k]){
                request.push(output[l]);
                break;
            }
        }
    }

    return request;
}

My_rowOrder参数指定的顺序输出对象数组:

[
    {
        Row: "2",
        Type: "Sony",
        Value: "PS4",
        Category: "Console"
    },
    {
        Row: "1",
        Type: "SSD",
        Value: "16GB",
        Category: "Disk Capacity"
    }
]

答案 1 :(得分:0)

试试这个:

function StringToArray(string) {
          var request = [[],[]];
          var pairs = string.split('&');
          for (var i = 0; i < pairs.length; i++) {
            var pair = pairs[i].split('=');
            request[pair[0].slice(-1)-1][decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
          }
          //console.log(request)
    }

答案 2 :(得分:0)

这可能对你有用......

<script>
var data = "My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console";
var array = new Array();
alert(JSON.stringify(URLToArray(data)));
function URLToArray(url) {
  var request = {};
  var pairs = url.substring(url.indexOf('?') + 1).split('&');
  for (var i = 0; i < pairs.length; i++) {
    var pair = pairs[i].split('=');
    request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  }
  return request;
}
</script>