[英]How can I add an array to an object but filter out all but one column for each array element?
I have an array on my page called answers
that looks like this: 我的页面上有一个名为answers
的数组,如下所示:
answers[{x: 1, r: true;},{x: 2,r: false;},{x: 3, r: true;}]
Hopefully I wrote this correctly. 希望我写得正确。 There are a variable number of rows in the answers array (this time it's three but it could be anything under ten). 答案数组中有一个可变数量的行(这次是三个,但可能是十个以下的任何行)。 Each row contains an x
field and a r
field. 每行包含一个x
字段和一个r
字段。
Can someone tell me how I can add the answers array (or recreate another similar one) but ONLY the r field of each row of the answers array to the following object: 有人可以告诉我如何添加答案数组(或重新创建另一个类似的数组),但只有答案数组的每一行的r字段为以下对象:
$scope.so.xHeaders[fromParams]
你可以在Underscore.js中使用pluck方法:
var newList = _.pluck(answers, 'r');
You can do something like that: 你可以这样做:
$scope.so.xHeaders = []
angular.forEach(answers, function(value, index) {
$scope.so.xHeaders.push({ r: value.r });
});
Depending on what you need there are a couple of ways of doing this. 根据您的需要,有几种方法可以做到这一点。
var answers = [{x: 1, r: true},{x: 2, r: false},{x: 3, r: true}]
1) If you just want an array of values: 1)如果您只想要一组值:
var arr = answers.map(function(el){
return el.r;
}, []);
console.log(arr) // [true, false, true]
2) If you want to return the objects but only containing the r
value: 2)如果要返回对象但仅包含r
值:
var arr = answers.map(function(el){
var obj = {};
obj.r = el.r;
return obj;
}, []);
(or shorter): (或更短):
var arr = answers.map(function(el){
return { r: el.r };
}, []);
console.log(arr) // [Object { r=true}, Object { r=false}, Object { r=true}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.