4

I have a array of json like the one I have given below

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

this has to be converted like

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

i am able to convert single dimension json to array using the map function

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

but converting it to work with multiple dimension is difficult. Is there any methods to convert json like this or any work around..?

1
  • Recursion may be a good place to start. Are you familiar with that idea? Commented Apr 20, 2016 at 16:26

2 Answers 2

4

You can use $.map() and map() with 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>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

2

Like this?

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 Comments

Looks fragile; what if you have braces inside the strings?
And what if you don't :) just being pragmatic !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.