Array of array to object - javascript

前端 未结 6 1439
不知归路
不知归路 2020-12-21 11:02

I am looping to convert the array of array to object, but the final object has only the last item in the object. I am getting confused because you cant push in an object lik

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-21 11:55

    You can do it with a single line:

    const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
    

    const show = msg => {console.log(JSON.stringify(msg));};
    const list = [
      [
        ['itemCode', 1],
        ['item', 'Pen'],
        ['cashier', 'Sam']
      ],
      [
        ['itemCode', 2],
        ['item', 'Eraser'],
        ['cashier', 'Kim']
      ]
    ];
    
    const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
    show(newResult);

提交回复
热议问题