H5W3
当前位置:H5W3 > 问答 > 正文

请问如何将二级嵌套数组合并成一级数组?

editDetails: [{

      causeName: '咳嗽001',
children: [{
productId: 7,
proCode: 'CP_20201012001',
proName: '产品1',
proPrice: 10,
number: 22,
price: 222
}, {
productId: 7,
proCode: 'CP_20201012001',
proName: '产品1',
proPrice: 10,
number: 22,
price: 222
}],
imageAttachment: '20201028014127383_oxxw29.jpg',
videoAttachment: '20201028014131101_WeChat_20201027132303.mp4'
}]
如何将这个数组合并成
editDetails: [{
causeName: '咳嗽001',
productId: 7,
proCode: 'CP_20201012001',
proName: '产品1',
proPrice: 10,
number: 22,
price: 222,
imageAttachment: ~~~~'20201028014127383_oxxw29.jpg',
videoAttachment: '20201028014131101_WeChat_20201027132303.mp4'
}, {
causeName: '咳嗽001',
productId: 7,
proCode: 'CP_20201012001',
proName: '产品1',
proPrice: 10,
number: 22,
price: 222,
imageAttachment: '20201028014127383_oxxw29.jpg',
videoAttachment: '20201028014131101_WeChat_20201027132303.mp4'
}]

回答


const a = [
  {
    children: [{
      productId: 7,
      proCode: 'CP_20201012001',
      proName: '产品1',
      proPrice: 10,
      number: 22,
      price: 222
    }, {
      productId: 7,
      proCode: 'CP_20201012001',
      proName: '产品2',
      proPrice: 10,
      number: 22,
      price: 222
    }],
    causeName: '咳嗽001',
    imageAttachment: '20201028014127383_oxxw29.jpg',
    videoAttachment: '20201028014131101_WeChat_20201027132303.mp4'
  }
]

function simpleFlatten(data) {
  return data.reduce((acc, cur) => {
    const { children = [] } = cur
    const extras = Object.keys(cur).filter(i => i !== 'children').reduce((acc, key) => {
      return {
        ...acc,
        [key]: cur[key]
      }
    }, {})
    return [
      ...acc,
      ...children.map(i => ({
        ...i,
        ...extras
      }))
    ]
  }, [])
}

console.log(simpleFlatten(a))
data.reduce((res, item) => {
    const parent = {...item};
    delete parent.children;
    return res.concat(item.children.map(child => ({...parent, ...child}))
}, []);

未经允许不得转载:H5W3 » 请问如何将二级嵌套数组合并成一级数组?

赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址