在jQuery中将多维哈希转换为数组

4
我有一个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"]]
]

我能够使用 map 函数将单维度的 JSON 转换为数组。
$.map( dimensions, function( value, index ) {
  ary.push([index, value])
});

但将其转换为适用于多维度的形式是困难的。有没有任何方法可以将这样的json转换,或者有任何解决方法..?


递归可能是一个不错的起点。你熟悉这个概念吗? - J E Carter II
2个回答

4

你可以使用 $.map()map() 来进行递归

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>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


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


2
看起来很脆弱;如果字符串中有括号怎么办? - Haroldo_OK
如果你不这样做怎么办 :),这只是务实而已! - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接