【问题标题】:Use object keys to divide javascript array of objects into multiple arrays使用对象键将对象的javascript数组划分为多个数组
【发布时间】:2019-02-15 05:34:20
【问题描述】:

假设我有一个这样的对象数组:

const array = [ 
{ year: 1971, temp1: 9.5, temp2: 8.0, temp3: 9.5 },
{ year: 1972, temp1: 15.0, temp2: 3.7, temp3: 94.3 },
...
{ year: 1999, temp1: 12.0, temp2: 31.0, temp3: 24.0 }
];

我如何将这个数组分成三个数组,其中包含以下键值对(所有对象都具有“年份”键值对,但每个数组都有不同的“临时”对):

const array1 = [ { year: 1971, temp1: 9.5}, { year: 1972, temp1: 15.0 } ... { year: 1999, temp1: 12.0 } ];

const array2 = [ { year: 1971, temp2: 8.0}, { year: 1972, temp2: 3.7 } ... { year: 1999, temp2: 31.0 } ];

const array3 = [ { year: 1971, temp3: 9.5}, { year: 1972, temp3: 94.3 } ... { year: 1999, temp3: 24.0  } ];

编辑:我一直在尝试循环遍历 Object.keys 以及数组的行,但我想出的所有内容都涉及多次循环遍历整个数组。

【问题讨论】:

  • “为我写这段代码”通常不是在 SO 上提问的方式。
  • 如果你给张贴者怀疑的好处,那就太好了。在发布之前,我确实花了很多时间研究解决方案。询问我尝试过的内容需要同样多的时间和空间,而不是急于得出我希望有人“为我编写这段代码”的结论。
  • 它的呈现方式是“为我编写这段代码”。为了提出改进或更好的解决方案,您尝试了什么以及为什么它不起作用非常重要。这是一个糟糕的问题,因为它不包含该信息。如果它不存在,那么您是否在此上花费 2 分钟或 2 天而不告诉任何人都没关系。关于您的编辑:如果不是因为该信息,我会诚实地为您提供一个在数组中循环多次的解决方案。所以,不是你想要的和你已经尝试过的。这就是信息很重要的原因。

标签: javascript arrays ecmascript-6


【解决方案1】:

一种解决方案可能是使用reduce(),并在reduce 的每个步骤上迭代object.keys() 时,您决定将新生成的对象放入哪个数组,格式为{year, temp}

const array = [ 
  {year: 1971, temp1: 9.5, temp2: 8.0, temp3: 9.5},
  {year: 1972, temp1: 15.0, temp2: 3.7, temp3: 94.3},
  {year: 1999, temp1: 12.0, temp2: 31.0, temp3: 24.0}
];

let res = array.reduce((acc, curr) =>
{
    Object.keys(curr).forEach((k, j) =>
    {
        if (j > 0)
        {
            acc[j - 1] = acc[j - 1] || [];
            acc[j - 1].push({year: curr.year, [k]: curr[k]});
        }
    });

    return acc;
}, []);

console.log(res);

【讨论】:

  • 优雅的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
相关资源
最近更新 更多