Skip to content Skip to sidebar Skip to footer

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 = [{'le

Solution 1:

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:

functionstrings_to_object(array) {

  // Initialize new empty arrayvar objects = [];


  // Loop through the arrayfor (var i = 0; i < array.length; i++) {

    // Create the object in the format you wantvar obj = {"letter" : array[i]};

    // Add it to the array
    objects.push(obj);
  }

  // Return the new arrayreturn 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.

Solution 2:

Don't assign each letter to a duplicate letter key (which really doesn't exist or make sense). Instead, use your array by storing each element in a separate item slot in the array, each having a type and a value:

[
    {
        type: "letter",
        value: "a"
    },
    {
        type: "letter",
        value: "b"
    },
    {
        type: "letter",
        value: "c"
    }
]

Or, as Obsidian Age commented, an array for letters (and then other arrays for other types of characters):

var letters = ['a', 'b', 'c'];

There's no one right way to store this data.

Post a Comment for "Converting String Array Into Javascript Object"