如何将数组转换为对象数组

时间:2017-08-01 19:58:16

标签: javascript arrays object

我有这段代码

var sourceData = somesourceData;

sourceData.forEach(function (sourceRow) {

   var dataRow = [];

   dataRow.push(sourceRow.desc);

   bodyQData.push(dataRow);

 });

产生这种结果

["desc1", "desc2", "etc"]

我想要得到这个结果

[
  {text: "desc1", style:"style1"},
  {text: "desc2", style:"style1"},
  {text: "etc", style:"style1"}
]

我知道如何做到这一点。

5 个答案:

答案 0 :(得分:2)

只需使用JavaScript Array map() Method

var arrOfObj =  array.map(function(item, index) {
    return {text: item, style:"style1"};
});

我希望对你有所帮助:)。

答案 1 :(得分:0)

您可以使用.map

var rows = sourceData.map(function(s) {
    return { text: s.desc, style: "style1" }
});

答案 2 :(得分:0)

var dataRow = [];
somesourceData.forEach(function (sourceRow) {
   dataRow.push({text:sourceRow.desc, style:"style1"});
 });

console.log(dataRow);

答案 3 :(得分:-1)

您可以从每个sourceRow创建一个对象,然后将其推送到一个数组,从而获得一个对象数组。

var sourceData = somesourceData;

sourceData.forEach(function(sourceRow) {

  var dataRow = [];

  dataRow = {
    text: sourceRow.desc.text,
    style: sourceRow.desc.text  
  }

  bodyQData.push(dataRow);

});

答案 4 :(得分:-1)

您将sourceRow.desc推送到数组,这是一个我相信的字符串

尝试以下代码

var sourceData = somesourceData;

sourceData.forEach(function (sourceRow) {

   var dataRow = [];

   dataRow.push({text:sourceRow.desc, style:"style1"});

   bodyQData.push(dataRow);

 });