Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
    
    
@adeneo - Then should we use object in JSON format? – neha soni Jul 1 '16 at 7:37
up vote 1 down vote accepted

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>';

share|improve this answer
    
This is not working?? – neha soni Jul 1 '16 at 10:54
    
It's working perfectly fine, as the snippet above shows. If it's not working for you, something else must be wrong. – adeneo Jul 1 '16 at 19:42
    
Yes might be the case. Because in browser console its working but giving error in my project. – neha soni Jul 2 '16 at 15:28

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>

share|improve this answer

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

share|improve this answer
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);
}
share|improve this answer

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);

}
share|improve this answer

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)
                      });
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.