【问题标题】:Convert array of objects into array of primitives (extracted from object properties)将对象数组转换为基元数组(从对象属性中提取)
【发布时间】:2026-02-04 23:25:01
【问题描述】:

考虑以下代码:

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 函数是什么?

到目前为止,我想出了以下几点:

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

但肯定有一种很好的单线方法可以做到这一点吗?

【问题讨论】:

  • 我投票结束这个问题,因为它属于代码审查。
  • @JamesHill Vote to close because the question is off-topic for Stack Overflow, not because it belongs somewhere else。因为它属于其他地方而投票结束可能会导致问题在两个地方被关闭的情况。这个问题不太适合 Code Review,虽然我认为它会成为主题(几乎没有),但我不认为这个问题与 Stack Overflow 无关。
  • 我不认为这是题外话。 OP 正在寻求帮助编写一个函数,也展示了他的方法。
  • @JamesHill There are other answers as well。整个“离题,因为它属于......”的密切原因是无稽之谈。其他网站的热度不影响 Stack Overflow 的热度。我还注意到您没有注册 Code Review,我建议您阅读我们的一些好问题和答案。这个问题吸引了诸如“这就是我会做的事情 ”之类的 SO 风格的答案,这样的答案在 Code Review 上是不受欢迎的。
  • @JamesHill 我们做个交易好吗?你出于不好的原因停止投票,我将停止对此发表评论。

标签: javascript arrays function object


【解决方案1】:

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

【讨论】: