0

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'
    }
]
Paul
  • 139,544
  • 27
  • 275
  • 264
blankface
  • 5,757
  • 19
  • 67
  • 114

1 Answers1

2

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.

Danziger
  • 19,628
  • 4
  • 53
  • 83