【问题标题】:How can I use forEach to transform a nested array into an object? [duplicate]如何使用 forEach 将嵌套数组转换为对象? [复制]
【发布时间】:2021-06-28 16:20:38
【问题描述】:

我可以使用 for 循环来实现这一点,但我不知道如何使用 forEach 来做同样的事情。

例如: var input = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]]; 调用该函数应导致:

{
  make : 'Ford',
  model : 'Mustang',
  year : 1964
}

【问题讨论】:

  • 为什么限制在forEach
  • Convert Array to Object 是规范副本。如果您的答案与那里的答案相同(即使用reduce),请勿回答此问题。这个问题询问关于使用forEach
  • 以数组为参数调用Object.fromEntries()

标签: javascript arrays foreach nested


【解决方案1】:

我们可以使用 forEach 和 Array destructuring 来实现这一点

var input = [
  ["make", "Ford"],
  ["model", "Mustang"],
  ["year", 1964],
];

const result = {};

input.forEach(([prop, value]) => {
  result[prop] = value;
});

/*--------- OR --(withour array destructuring)-------------
input.forEach(internalArr => {
  result[internalArr[0]] = internalArr[1];
});
*/

console.log(result);

您也可以使用Array.prototype.reduce 实现此目的。 Array.prototype.reduce 是完成这项工作的正确工具。

var input = [
  ["make", "Ford"],
  ["model", "Mustang"],
  ["year", 1964],
];

const result = input.reduce((acc, curr) => {
  const [prop, value] = curr;
  acc[prop] = value;
  return acc;
}, {});

console.log(result);

【讨论】:

  • 我们有许多使用reduce 的“更好选择”的副本以及其他解决方案。此问题使用forEach 寻求答案。
  • @HereticMonkey 也使用 forEach 添加了解决方案
  • 我想说Array.prototype.reduce 不是 正确的工具。真的,它与其他循环构造没有什么不同。
  • @appleapple 如果你能解释一下,我会很高兴,为什么Array.prototype.reduce 不是正确的工具。可能有什么我不知道的。这样我就可以从你那里学到新的东西。 ☺☺☺
  • @DeC 这就是我突出显示 the 的原因。我只是说它与其他循环结构相比并没有真正的好处。
【解决方案2】:

您可以对目标对象进行闭包,并使用来自convert 的返回函数迭代数组。

const
    convert = target => ([key, value]) => target[key] = value,
    input = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]],
    output = {};

input.forEach(convert(output));

console.log(output);

【讨论】:

    猜你喜欢
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2017-11-15
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多