I'm trying to convert the following array of strings:
["one", "two", "three"]
to an array of JSON objects with a specific key of, for instance, number, as follows:
[
{
number: 'one'
},
{
number: 'two'
},
{
number: 'three'
}
]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.