gpt4 book ai didi

javascript - 将对象数组转换为基元数组(从对象属性中提取)

转载 作者:行者123 更新时间:2023-11-30 12:26:56 24 4
gpt4 key购买 nike

考虑以下代码:

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]

什么是我能写的最短、最简洁的 convert 函数,它会给我显示的 output

到目前为止,我已经想出了以下内容:

function convert(input) {
var output = [];
input.forEach(function(obj) {
output.push(obj.x, obj.y);
});
return output;
}

但肯定有一种很好的单行方式来做到这一点?

最佳答案

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

关于javascript - 将对象数组转换为基元数组(从对象属性中提取),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com