js如何将二维数组嵌套二维数组转换成一维数组?

二维数组嵌套二维数组转换成一维数组?

list(newV) {
  this.newList = newV;
  this.OrderItems = this.newList.map(item => item.OrderItems);
  console.log('OrderItems', this.newList);
}

返回来的数据处理
clipboard.png

通过map遍历出来, 里面还嵌套二维数组, 下面不知道如何将数组合并成一维数组

clipboard.png

阅读 5.5k
4 个回答
this.OrderItems = [].concat(...this.newList.map(item => item.OrderItems));
function flatten(arr) {
    var res = [];
    arr.map(item => {
        if(Array.isArray(item)) {
            res = res.concat(flatten(item));
        } else {
            res.push(item);
        }
    });
    return res;
}

封装了一个函数, 直接调用就可以了

function steamroller(arr) {
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      newArr.push(...steamroller(arr[i]));
    } else {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

试试 console.log([...this.newList, ...this.OrderItems])

推荐问题