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
  • 36,413
  • 9
  • 66
  • 103
user2282534
  • 39
  • 2
  • 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
  • 42,889
  • 6
  • 74
  • 90
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
  • 29,350
  • 9
  • 53
  • 99
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,573
  • 5
  • 23
  • 43
0

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

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