I have plain string array and I want to convert it to JavaScript object basically adding a key to the values.
My array
var myArr = ["a", "b", "c"]
var myObj = [{"letter":"a", "letter":"b", "letter":"c"}]
This is how I would implement that. You can probably make it less verbose by not even making the var obj, but for the purpose of illustration I have written it as follows:
function strings_to_object(array) {
// Initialize new empty array
var objects = [];
// Loop through the array
for (var i = 0; i < array.length; i++) {
// Create the object in the format you want
var obj = {"letter" : array[i]};
// Add it to the array
objects.push(obj);
}
// Return the new array
return objects;
}
Output:
[ { letter: 'a' }, { letter: 'b' }, { letter: 'c' } ]
I realize the output is slightly different in that your output is a single array with one objet. The problem there is that the object has several repeating keys. Just like in your original array (of size 3), your output array should be of size 3. Each object will have a "letter" key.