首页 > 解决方案 > 使用旧数组中的两列创建新数组

问题描述

我有一个数组如下:

items = [
{"year": 2010, "month": 11, "day":23}
{"year": 2009, "month": 10, "day":15}
{"year": 2009, "month": 10, "day":10} //added after my edit below
]

我想创建一个只有 2 列的新数组,如下所示:

newArarry = [
{"year": 2010, "month": 11}
{"year": 2009, "month": 10}
]

现在我正在尝试使用 .map() 并且它不起作用:

const newArray = [];
newArray.map({
    year: items.year,
    month: items.month
});

编辑

在遵循以下答案之一后,我意识到我忘了提及我还需要将结果过滤为唯一的行。现在我只选择年份和月份列,我得到多个重复的行

标签: javascriptarraysobjectecmascript-6

解决方案


现在我正在尝试使用 .map() 并且它不起作用

  • 因为 newArray 有长度0,你正试图映射它
  • map 接受回调,但您正在传递对象
  • 不将地图的输出分配给任何变量

let items = [{"year": 2010, "month": 11, "day":23},{"year": 2009, "month": 10, "day":15}]

let final = items.map(({day,...rest}) => ({...rest}))

console.log(final)


推荐阅读