Krishna Kiriti Krishna Kiriti - 3 years ago 185
Javascript Question

converting string array into javascript object

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"]


I want it Like

var myObj = [{"letter":"a", "letter":"b", "letter":"c"}]


Let me know the possibilities.
Thank you

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download