问题
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