【问题标题】:converting multidimensional hash to array in jquery在jQuery中将多维哈希转换为数组
【发布时间】:2016-04-20 16:22:52
【问题描述】:

我有一个 json 数组,就像我在下面给出的那样

[
    {"Name": {"xxx": [{"I": "FORENAME"} , {"I": "Surname"}]}},
    {"EmailAddress":{"I": "yyy"}},
    {"[ID]": {"I": "zzz"}},
    {"[Company]": {"I": "aaa"}}
]

这必须像这样转换

[
    ["Name", ["xxx", [["I", "FORENAME"], ["I", "Surname"]]]],
    ["EmailAddress", ["I", "yyy"]],
    ["[ID]", ["I", "zzz"]],
    ["[Company]", ["I", "aaa"]]
]

我可以使用 ma​​p 函数将单维 json 转换为数组

$.map( dimensions, function( value, index ) {
  ary.push([index, value])
});

但将其转换为与多维度一起使用是困难的。有什么方法可以像这样转换json或任何解决方法..?

【问题讨论】:

  • 递归可能是一个很好的起点。你熟悉这个想法吗?

标签: jquery arrays json


【解决方案1】:

您可以使用 $.map()map()recursion

var dimensions = [{
  "Name": {
    "xxx": [{
      "I": "FORENAME"
    }, {
      "I": "Surname"
    }]
  }
}, {
  "EmailAddress": {
    "I": "yyy"
  }
}, {
  "[ID]": {
    "I": "zzz"
  }
}, {
  "[Company]": {
    "I": "aaa"
  }
}];

function gen(data) {
  // checking data is an object
  if (typeof data == 'object') {
    // checking it's an array
    if (data instanceof Array)
      // if array iterating over it
      return data.map(function(v) {
        // recursion
        return gen(v);
      });
    else
      // if it's an object then generating array from it
      return $.map(data, function(value, index) {
        // pushing array value with recursion
        return [index, gen(value)];
      });
  }
  // returning data if not an object
  return data;
}

document.write('<pre>' + JSON.stringify(gen(dimensions), null, 3) + '</pre>')
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    像这样?

    var oldOBJ = [
        {"Name": {"xxx": [{"I": "FORENAME"} , {"I": "Surname"}]}},
        {"EmailAddress":{"I": "yyy"}},
        {"[ID]": {"I": "zzz"}},
        {"[Company]": {"I": "aaa"}}
    ]
    
    var newOBJ =JSON.parse(JSON.stringify(oldOBJ).replace(/\{/g,"[").replace(/\}/g,"]").replace(/:/g,","));
    
    document.write(JSON.stringify(newOBJ));

    【讨论】:

    • 看起来很脆弱;如果字符串中有大括号怎么办?
    • 如果你不这样做怎么办 :) 只是务实!
    猜你喜欢
    • 2019-07-14
    • 2016-05-08
    • 2019-10-27
    • 2019-05-23
    • 2012-10-29
    • 2010-12-11
    • 2018-10-27
    • 2011-01-16
    • 2015-09-15
    相关资源
    最近更新 更多