bsh
bsh

Reputation: 447

Convert Array To a Specific Object

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

Answers (3)

Pranav C Balan
Pranav C Balan

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

Nenad Vracar
Nenad Vracar

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

Jamiec
Jamiec

Reputation: 136104

With a 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)

Upvotes: 4

Related Questions