Reputation: 447
What is the best way to convert this array :
array=['a', 'b', 'c', 'd']
to
$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}
]}
Upvotes: 1
Views: 61
Reputation: 115222
Use Array#map
method.
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);
Upvotes: 2
Reputation: 122047
You can use reduce
method to return object.
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)
Upvotes: 1