转换此数组的最佳方法是什么:
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}
]}
答案 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)