2

I'm trying to convert a JavaScript object to an other.

Let's say that my JavaScript input object looks like this :

$scope.name_person= [{
    "firstName":"Jean","lastName":"Smith"
 }]

The output should be like this :

 $scope.name_perso=  [{ 

  "values":[
       "firstName":"Jean","lastName":"Smith"
           ]
  }]

this is my code :

function convert(arr) {
    return $.map(unique(arr), function(name){
        return {
            values: $.grep(arr, function(item){
                return item.name == name
            })
        } 
    });
}

function unique(arr) {
    var result = [];
    $.map(arr, function(item){
        if ($.inArray(item.name, result))
            result.push(item.name);
    })
    return result;
}

$scope.data=convert($scope.name_person);

Any Adivice ?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360

2 Answers2

0
 $scope.name_person=  [{ 

  "values":[
       "firstName":"Jean","lastName":"Smith"
           ]
  }]

You are trying to create an associative array but, associative arrays are not supported in Javascript, for that you need to use objects(which are also special type of arrays with key:value pair).

What you can do is :

    var $scope = {};
    $scope.newObject = [];
    $scope.namePerson = [{
        "firstName":"Jean","lastName":"Smith"
    }];
    $scope.newObject.push(
        {
            "values": $scope.namePerson[0]
        }
    );

    console.log($scope.newObject);

This will return

[{ 
   "values":{
       "firstName":"Jean","lastName":"Smith"
       }
}]
Vaibhav Jain
  • 687
  • 4
  • 15
  • Thx for your answer but i get this error: Uncaught SyntaxError: Unexpected token . And my name Person doesn't contains one element :o – Heerr König Apr 26 '16 at 16:25
0

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
  
  $scope.name_person= [{
    "firstName":"Jean","lastName":"Smith"
 }];
   var array = [{'values':[]}];
  angular.forEach($scope.name_person,function(item,i){
         array[0].values.push(item);
      });
  
  $scope.name_person = [];
  $scope.name_person = array;
  console.log(array);
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">

     <pre>{{name_person | json}}</pre>
</div>

try this

  var array = [{'values':[]}];
  angular.forEach($scope.name_person,function(item,i){
     array[0].values.push(item);
  });

  $scope.name_person = [];
  $scope.name_person = array;
Hadi J
  • 16,989
  • 4
  • 36
  • 62