0
for (var k = 0; k < arr.length; k++){
    var item = new Array();
    item = {
        subtitle: arr[k]
    }
}

How to convert array of string to array of object am using

for(var i in data){
    arr.push(data[i]);
}

to get array of strings but need to convert array of strings to array of object.

George
  • 35,662
  • 8
  • 61
  • 98
user2282534
  • 39
  • 1
  • 8

4 Answers4

1

Use map when you want to create a new array from a source one by modifying it's values.

var arrayOfObjects = data.map(function (item) {
    return { item: item };
});
plalx
  • 41,415
  • 5
  • 69
  • 87
0

Two ways:

var arrOfStrs = ["1","2","3","4"];

// first way - using the regular for
var arrObj1 = [];

for(var i = 0 ; i < arrOfStrs.length; i++)
{
    arrObj1.push({item: arrOfStrs[i]});
}

console.log(arrObj1);

// second way - using for...in
var arrObj2 = [];

for(var key in arrOfStrs)
{
    arrObj2.push({item: arrOfStrs[key]});
}

console.log(arrObj2);

JSFIDDLE.

Amir Popovich
  • 28,017
  • 9
  • 48
  • 94
0

Considering you have an array of strings like:

var arr = ["abc", "cde", "fgh"];

you can convert it to array of objects using the following logic:

var arrOfObjs = new Array(); //this array will hold the objects
var obj = {};   //declaring an empty object
for(var i=0; i<arr.length; i++){  //loop will run for 3 times
    obj = {}; //renewing the object every time to avoid collision
    obj.item = arr[i];  //setting the object property item's value
    arrOfObjs.push(obj);  //pushing the object in the array
}

alert(arrOfObjs[0].item);  //abc
alert(arrOfObjs[1].item);  //cde
alert(arrOfObjs[2].item);  //fgh

See the DEMO here

Abdul Jabbar
  • 2,505
  • 4
  • 20
  • 43
0

var arrOfStrs = ["1", "2", "3", "4"];

var data = Object.entries(arrOfStrs).map(([key, value]) => ({
  [key]: value
}))
console.log(data)
barbsan
  • 3,328
  • 11
  • 20
  • 28
poran
  • 31
  • 1
  • 9