简体   繁体   中英

Convert Json object array to list of property values in angularjs

I have this list of objects -

var o_list = [{id:1,name:jo},{id:2,name:mo}];

and I want to extract something like this -

var list = [1,2]

Is there anything already built or how can we implement this.

You can just map it

 var o_list = [{id:1,name:"jo"},{id:2,name:"mo"}]; var list = o_list.map(x => x.id); document.body.innerHTML = '<pre>' + JSON.stringify(list, 0, 4) + '</pre>'; 

you can do this using filters https://docs.angularjs.org/api/ng/filter/filter

 var myApp = angular.module('myApp', []); myApp.controller("myCtrl", ['$scope', '$filter', function($scope, $filter) { $scope.values = [{ id: 1, name: 'asdas' }, { id: 2, name: 'blabla' }]; // this is how you use filters in your script console.log($filter('extract')($scope.values)); } ]); myApp.filter('extract', function() { return function(input) { return input.map(x => x.id); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="myCtrl"> <ol ng-repeat="id in values | extract"> <li ng-bind="id"></li> </ol> </div> </div> 

You can use only javscript forEach array method to get desired result

var o_list = [{id:1,name:'jo'},{id:2,name:'mo'}];

var list =[];
o_list.forEach(function(item){
list.push(item.id)

})

console.log(list)

JSFIDDLE

var o_list = [{id:1,name:jo},{id:2,name:mo}];
var list = [];

for(i = 0; i < o_list.length; i++){
   list.push(o_list[i].id);
}

you can use this simple for loop

var o_list = [{id:1,name:'jo'},{id:2,name:'mo'}];
var s=[];
for (var i=0;i< o_list.length;i++){
 s.push(o_list[i].id);

}

Alternate you can use underscore.js each method to get results

      var o_list = [{id:1,name:'jo'},{id:2,name:'mo'}];

        var list =[];
        _.each(o_list, function(d){
                         list.push(d.id)
                      });

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