Just use Array.prototype.map() to iterate over all the elements in the array
and create a new one while converting them to an object
with the structure you need.
You can use ES6 to do it with fewer lines of code, but I have also provided a version with ES5:
// ES6:
const arrayOfObjectsES6 = ["one", "two", "three"].map(number => ({ number }));
console.log(arrayOfObjectsES6);
// ES5:
var listOfObjectsES5 = ["one", "two", "three"].map(function(value) {
return { number: value };
});
console.log(listOfObjectsES5);
Then, you can just use JSON.stringify()
to get the JSON string
representation of it:
JSON.stringify(arrayOfObjectsES6);
If you want to be able to reuse this functionality using keys other than "number"
:
function getArrayOfObjectsES6(values, key) {
return values.map(value => ({ [key]: value }))
}
console.log( JSON.stringify(getArrayOfObjectsES6(["one", "two", "three"], 'ES6')) );
function getArrayOfObjectsES5(values, key) {
return values.map(function(value) {
var obj = {};
obj[key] = value;
return obj;
});
}
console.log( JSON.stringify(getArrayOfObjectsES6(["one", "two", "three"], 'ES5')) );
Note you can also use a regular for
, but I think map()
is the cleaner and most concise option here.