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

流过昼夜 提交于 2020-07-05 05:13:34

问题


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?!


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/42413060/converting-an-array-of-arrays-to-list-of-json-objects-instead-of-json-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!