将数组转换为特定对象

时间:2017-02-09 09:09:06

标签: javascript arrays object

转换此数组的最佳方法是什么:

array=['a', 'b', 'c', 'd']

$scope.editcity = {
      cities : [
        {id: 1, name: "a", selected: false},
        {id: 2, name: "b", selected: false},
        {id: 3, name: "c", selected: false},
        {id: 4, name: "d", selected: false}
]}

3 个答案:

答案 0 :(得分:4)

使用map

var array=['a', 'b', 'c', 'd']

var $scope = {} // just for this test - you wont need this line
$scope.editcity = {
      cities : array.map(function(c,i){
        return {
            id: i+1,
            name: c,
            selected:false
          }
      })
};

console.log($scope.editcity)

答案 1 :(得分:2)

使用Array#map方法。

var array = ['a', 'b', 'c', 'd']

$scope.editcity = {
  cities : array.map(function(v, i){
    return  {
       id : i + 1,
       name : v,
       selected : false
    }
  })
}

var array = ['a', 'b', 'c', 'd']

var editcity = {
  cities: array.map(function(v, i) {
    return {
      id: i + 1,
      name: v,
      selected: false
    }
  })
}

console.log(editcity);

答案 2 :(得分:1)

您可以使用reduce方法返回对象。



var array=['a', 'b', 'c', 'd']

var editcity = array.reduce(function(r, e, i) {
  r.city = (r.city || []).concat({id: i + 1, name: e, selected: false})
  return r
}, {})

console.log(editcity)