Wasim Thabraze
Wasim Thabraze

Reputation: 810

Converting an array of arrays to list of JSON objects instead of JSON strings

I'm trying to convert an array of arrays to a list of JSON objects.

var headers = ['first name','last name','age']

var data = [ [ 'John', 'Gill', '21' ], [ 'Sai', 'Varun', '21' ] ]

When we use the above two lists to generate a list of JSON's, output will be like,

[ { 'First name': 'John', 'Last name': 'Gill', age: '21' },
  { 'First name': 'Sai', 'Last name': 'Varun', age: '21' } ]

But I'm in need of the output to be as, (double quoted strings and the JSON should not be a string but should be a JSON object)

[ {"First name":"John","Last name":"Gill","age":"21"},
  {"First name":"Sai","Last name":"Varun","age":"21"} ]

I tried using JSON.stringify but the result won't be a JSON object right, it'll be a JSON string which would prevent accessing each of the JSON's from the list as a whole.

I have gone through many such answers but in vain. Can someone shed some light on this?!

Upvotes: 0

Views: 2768

Answers (3)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

DEMO

var headers = ['first name','last name','age'];

var data = [['John', 'Gill', '21'],['Sai', 'Varun', '21']];

var res = data.map(function(item) {
  var obj = {};
  for (var i in headers) {
    obj[headers[i]] = item[i];
  }
  return obj;
});

console.log(res);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386522

You could generate an array with the objects first and the stringify the array.

var headers = ['first name', 'last name', 'age'],
    data = [['John', 'Gill', '21'], ['Sai', 'Varun', '21']],
    result = data.map(function (a) {
        var object = {};
        headers.forEach(function (k, i) {
            object[k] = a[i];
        });
        return object;
    });
    
console.log(JSON.stringify(result));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6

var headers = ['first name', 'last name', 'age'],
    data = [['John', 'Gill', '21'], ['Sai', 'Varun', '21']],
    result = data.map(a => headers.reduce((r, k, i) => Object.assign(r, { [k]: a[i] }), {}));
    
console.log(JSON.stringify(result));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 4

Mirko Vukušić
Mirko Vukušić

Reputation: 2121

var headers = ['first name','last name','age']
var data = [ [ 'John', 'Gill', '21' ], [ 'Sai', 'Varun', '21' ] ]

function createItem(item) {
    newObject = {}
    item.map((val,i)=>newObject[headers[i]]=val)
	return newObject
}

console.log(data.map(item=>createItem(item)))

Upvotes: 2

Related Questions