js 循环数组生成一个新的对象型数组

比如有数据

years = ['2018','2019','2020','2021']
sale = [ 1000,2000,3000,4000]

要生成一个对象型数组

[{
 x:'2018',
 y:1,
 'text':'1000',
 'other_key':'other_value',
} 
...
{
 x:'2021',
 y:1,
 'text':'4000',
 'other_key':'other_value',
}]

我想用 数组的map来着。可是函数体里面又不能使用 冒号。咋解?
谢谢!

阅读 2.5k
2 个回答
    let years = ['2018', '2019', '2020', '2021'],
        sale = [1000, 2000, 3000, 4000],
        res = [];
    sale.map((ele, index) => {
        res.push({
            x: years[index],
            y: 1,
            'text': ele + "",
            'other_key': 'other_value',
        });
    });
    console.log(res);
const years = ["2018","2019","2020","2021"];
const sale = [1000, 2000, 3000, 4000];

const result = years.map((year, i) => ({
    x: year,
    y: 1,
    text: sale[i].toString(),
    other_key: "other_value"
}));

console.log(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题