简体   繁体   中英

Convert a JavaScript object to an other format

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 ?

 $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"
       }
}]

 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM