我有對象的此列表 -轉換JSON對象數組屬性的值的列表中angularjs
var o_list = [{id:1,name:jo},{id:2,name:mo}];
和我想提取這樣的事情 -
變種列表= [1,2 ]
有什麼已經建成的,或者我們該如何實現這一點。
我有對象的此列表 -轉換JSON對象數組屬性的值的列表中angularjs
var o_list = [{id:1,name:jo},{id:2,name:mo}];
和我想提取這樣的事情 -
變種列表= [1,2 ]
有什麼已經建成的,或者我們該如何實現這一點。
您可以只映射它
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>';
這不行? –
正如上面的代碼片段所顯示的,它工作得很好。如果它不適合你,其他的東西一定是錯的。 – adeneo
是的,可能是這種情況。因爲在瀏覽器控制檯中它的工作,但在我的項目中給錯誤。 –
,你可以做到這一點使用過濾器 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>
只能使用javscript forEach
陣列的方法,從而獲得所需結果
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)
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);
}
你可以使用這個簡單的for循環
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);
}
替代你可以使用underscore.js每種方法得到結果
var o_list = [{id:1,name:'jo'},{id:2,name:'mo'}];
var list =[];
_.each(o_list, function(d){
list.push(d.id)
});
[沒有這種東西作爲「JSON對象」](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – adeneo
@adeneo - 然後我們應該使用JSON格式的對象嗎? –