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'
    }
]
2
  • Possible duplicate of Convert array to JSON Commented Feb 1, 2018 at 0:44
  • 2
    That's just an array of objects, not JSON. Iterate the array, and .push({number:item}); Commented Feb 1, 2018 at 0:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.