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.

2

4 Answers 4

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 };
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

0

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

var data = Object.entries(arrOfStrs).map(([key, value]) => ({
  [key]: value
}))
console.log(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.