0

I have array of JSON objects as follows:

var out = [{
  1: {
    name: 'Name 1',
    id: 'one'

  }
}, {
  2: {
    name: 'Name 2',
    id: 'two'
  }
}];

I am trying to convert this to 2-D array as:

var out = [[1,object],[2,object]];

I tried to use json.encode(out) , any methods or approaches for converting this?

4 Answers 4

4

simply try

var output  = out.map(function(val){
  var keyName = parseInt(Object.keys(val)[0],10);
  var value =  val[keyName];
  return [keyName, value];
});

DEMO

var out = [{
  1: {
    name: 'Name 1',
    id: 'one'
  }
}, {
  2: {
    name: 'Name 2',
    id: 'two'
  }
}];

var output = out.map(function(val) {
  var keyName = parseInt(Object.keys(val)[0],10);
  var value = val[keyName];
  return [keyName, value];
});

document.body.innerHTML += JSON.stringify(output,0,4);

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

1 Comment

you have forgot that "1" and "2" should be numbers
3

You can use map() and Object.keys()

var out = [{
  1: {
    name: 'Name 1',
    id: 'one'

  }
}, {
  2: {
    name: 'Name 2',
    id: 'two'
  }
}];

var res = out.map(function(v) {
  var key = Object.keys(v)[0];
  return [parseInt(key,10), v[key]];
})

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

1 Comment

you have forgot that "1" and "2" should be numbers
3

A proposal for a more dynamic data structure, without stress to the first key

var out = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }],
    result = [];

out.forEach(function (a) {
    Object.keys(a).forEach(function (k) {
        result.push([+k, a[k]]);
    });
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

1 Comment

you have forgot that "1" and "2" should be numbers
1

To meet your requirement: ([[1,object],[2,object]]) "1" and "2" keys should be numbers:

var result = out.map(function(v){
    var k = Object.keys(v)[0];
    return [parseInt(k),v[k]];
});

console.log(JSON.stringify(result,0,4));

The console.log output:

[
    [
        1,
        {
            "name": "Name 1",
            "id": "one"
        }
    ],
    [
        2,
        {
            "name": "Name 2",
            "id": "two"
        }
    ]
]

Comments

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.