将数组中的字符串转换为对象

时间:2015-11-04 12:51:01

标签: javascript jquery arrays

我从服务器收到以下格式的字符串数组:

var fruitsStrings = ["apple", "banana", "orange" ];

是否可以将其转换为对象数组,如下所示?

var fruitsObjects = [
    {
        fruit: "apple"
    },
    {
        fruit: "banana"
    },
    {
        fruit: "orange"
    }
];

所有对象属性都是相同的。很高兴使用纯JavaScript或jQuery。我尝试过使用jquery.extend但是因为这会在每个值之前添加唯一ID,但这并不适合我的目的。

谢谢。

6 个答案:

答案 0 :(得分:1)

var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];

fruitsStrings.forEach(function (item) {
    fruitsObjects.push({ fruit: item });
});

Working demo.

答案 1 :(得分:1)

您可以使用.map

var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects  = fruitsStrings.map(function( val, i ) {
  return {fruit:val};
});
document.write(JSON.stringify(fruitsObjects));



    var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects  = fruitsStrings.map(function( val, i ) {
  return {fruit:val};
});
document.write(JSON.stringify(fruitsObjects));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

试试这个:

{{1}}

答案 3 :(得分:1)

一个简单的Array.prototype.map会:

var fruitsStrings = ["apple", "banana", "orange"],
    fruitsArray = fruitsStrings.map(function (a) { return { fruit: a } });
document.write('<pre>' + JSON.stringify(fruitsArray, 0, 4) + '</pre>');

答案 4 :(得分:1)

您也可以使用此功能指定密钥。

function toObjects(key,arr) {
  var objects = [];
  for (var i = 0; i < arr.length; ++i){
    var obj = {};
    obj[key] = arr[i];
    objects[i] = obj;
  }
  return objects;
}
var fruitsStrings = ["apple", "banana", "orange" ];
toObjects('fruit',fruitsStrings);
// [{fruit: "apple"},{fruit: "banana"},{fruit: "orange"}]

答案 5 :(得分:1)

试试这个:

var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];

fruitsStrings.map(function(v,i){
    fruitsObjects.push({'fruit':v});
});

console.log(fruitsObjects);

Working Demo