javascript - Javascript - 从旧数组中创建包含两个列的新数组

我有一个如下的数组:


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


});



时间:

你没有正确调用Array#map

  • 你需要在源数组中调用: items
  • 你需要提供一个函数作为参数,
  • Array#map返回一个新数组,该数组是对原始数组的每个成员执行的函数的结果,

items = [


{"year": 2010,"month": 11,"day":23},


{"year": 2009,"month": 10,"day":15}


]



const newArray = items.map(item => ({


 year: item.year,


 month: item.month


}));



console.log(newArray)

映射操作从A转换到B-在这个例子中 {"year": 2010,"month": 11,"day":23}{"year": 2010,"month": 11 } 对数组运行.map会给你映射操作的结果。

数组方法的.map()接受回调,返回值会被用来构造新数组,错误地你将它传递给一个对象而不是函数,要解决这个问题,你可以使用.map()和一些对象解构:


const items = [


 {"year": 2010,"month": 11,"day":23},


 {"year": 2009,"month": 10,"day":15}


];



const result = items.map(({ year, month }) => ({year, month}));



console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

映射需要回调。


var newArray = items.map(function (item) {


 return {


 year: item.year,


 month: item.month


 };


});



请更正项目数组,包含多个元素/值的数组必须是逗号分隔,


var items = [


 {"year": 2010,"month": 11,"day":23},


 {"year": 2009,"month": 10,"day":15}


 ]


 const newArray = [];


 items.map(i=>{


 newArray.push({year: i.year, month: i.month});


 });


 console.log(newArray)



...