I have an array of arrays that I want to turn into an array of objects in JavaScript.
Input:
[
[ "foo", 1.0 ],
[ "bar", 3.2 ],
[ "baz", 2.1 ]
]
Output:
[
{ "foo": 1.0 },
{ "bar": 3.2 },
{ "baz": 2.1 }
]
I have an array of arrays that I want to turn into an array of objects in JavaScript.
Input:
[
[ "foo", 1.0 ],
[ "bar", 3.2 ],
[ "baz", 2.1 ]
]
Output:
[
{ "foo": 1.0 },
{ "bar": 3.2 },
{ "baz": 2.1 }
]
Use array.map
to do something like this perhaps:
arr = [
["foo", 1.0],
["bar", 3.2],
["baz", 2.1]
]
console.log(arr.map(e => ({[e[0]]: e[1]})));
This code will work on All the browsers:
Plain native code for the understanding of conversion(code is not optimized though):
var ArrayObject = [
["foo", 1.0],
["bar", 3.2],
["baz", 2.1]
];
var OutputArray = []
for(var i=0;i<ArrayObject.length;i++){
var arrayObject = {}
var ObjectProperty = ArrayObject[i][0];
var ObjectValue = ArrayObject[i][1];
arrayObject[ObjectProperty] = ObjectValue;
OutputArray.push(arrayObject);
}