1

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.

2

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's working perfectly fine, as the snippet above shows. If it's not working for you, something else must be wrong.
Yes might be the case. Because in browser console its working but giving error in my project.
2

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>

Comments

1

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

Comments

0

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

Comments

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

Comments

0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.