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.
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 asked Jun 30, 2016 at 13:50 neha sonineha soni 2213 silver badges12 bronze badges 2- There's no such thing as a "JSON Object" – adeneo Commented Jun 30, 2016 at 13:51
- @adeneo - Then should we use object in JSON format? – neha soni Commented Jul 1, 2016 at 7:37
6 Answers
Reset to default 2You 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/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./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>
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)
});
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);
}