最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert Json object array to list of property values in angularjs - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

6 Answers 6

Reset to default 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>';

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

}
发布评论

评论列表(0)

  1. 暂无评论