将值数组转换为以该值作为属性的对象数组

时间:2020-06-18 19:33:31

标签: javascript ecmascript-6

假设我有一个像[0, 1, 2, 3]这样的数组。

我想要一个将其转换为[{num: 0}, {num: 1}, {num: 2}, {num: 3}]的函数(使用数组值作为特定键的值)。我该如何在没有for循环的情况下做到这一点?

3 个答案:

答案 0 :(得分:2)

使用map()方法:

var array1 = [0, 1, 2, 3];
var array2 = array1.map(function(ele) { return {'num':ele};});
console.log(array2);

结果:

[[object Object] {
  num: 0
}, [object Object] {
  num: 1
}, [object Object] {
  num: 2
}, [object Object] {
  num: 3
}]

Working Demo online.

答案 1 :(得分:0)

您可以使用map运算符,如下所示-

let arr = [0, 1, 2, 3];
// mapping each entry of list to a key:value pair using map()
arr = arr.map(el => {
  return {
    'num': el
  }
});
// you can use normal function() instead of arrow functions if you using ES5
/*
arr = arr.map(function(el) {
  return {
    num: el
  }
});
*/

console.log(arr);

您可以详细了解map() here

希望这会有所帮助!

答案 2 :(得分:-1)

您可以使用map()运算符-

var arr = [0, 1, 2, 3];

var newArr = arr.map(num => ({num}));

console.log(newArr);