[英]Convert array of objects into array of primitives (extracted from object properties)
Consider the following code: 请考虑以下代码:
var input = [{x: 1, y: 6}, {x: 4, y: 3}, {x: 9, y: 2}];
var output = convert(input);
console.log(output); // = [1, 6, 4, 3, 9, 2]
What is the shortest, most concise convert
function I can write that will give me the output
shown? 什么是我能编写的最短,最简洁的
convert
函数,它会给我显示的output
?
So far I've come up with the following: 到目前为止,我已经提出以下建议:
function convert(input) {
var output = [];
input.forEach(function(obj) {
output.push(obj.x, obj.y);
});
return output;
}
But surely there's a nice one-liner way of doing this? 但肯定有一个很好的单行方式吗?
With Array.prototype.reduce
method it will save you two lines of code: 使用
Array.prototype.reduce
方法,它将为您节省两行代码:
function convert(arr) { return arr.reduce(function(prev, curr) { return prev.concat(curr.x, curr.y); }, []); } var input = [{x: 1, y: 6}, {x: 4, y: 3}, {x: 9, y: 2}]; document.write(JSON.stringify( convert(input) ));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.