如何将字符串数组转换为对象数组?

时间:2014-09-08 12:24:27

标签: javascript

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

如何使用

将字符串数组转换为对象数组
for(var i in data){
    arr.push(data[i]);
}

获取字符串数组但需要将字符串数组转换为对象数组。

4 个答案:

答案 0 :(得分:1)

如果您想通过修改新数组的值来创建新数组,请使用map

var arrayOfObjects = data.map(function (item) {
    return { item: item };
});

答案 1 :(得分:0)

两种方式:

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

答案 2 :(得分:0)

考虑到你有一个字符串数组,如:

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

您可以使用以下逻辑将其转换为对象数组:

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

答案 3 :(得分:0)

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

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