简体   繁体   中英

How to properly filter the array

Hello everyone there is an array of data of this kind

const arrayPat = [
    {pat: '111', res: 'qwe', tag: '1'},
    {pat: '111', res: 'sda', tag: '2'},
    {pat: '111', res: 'xzc', tag: '3'},
    {pat: '111', res: 'cej', tag: '4'},
    {pat: '222', res: 'qwd', tag: '5'},
    {pat: '222', res: 'asd', tag: '6'},
  ]

need to get something like that

  const resultArray: any = [{pat: '111', res: ['qwe', 'sda', 'xzc', 'cej'], tag: '1'},{pat: '222', res: ['qwe', 'asd'], tag: '1'}]

If exactly what is mentioned in the question is needed, we can slightly tweak the code

 const arrayPat = [{ pat: '111', res: 'qwe', tag: '1' }, { pat: '111', res: 'sda', tag: '2' }, { pat: '111', res: 'xzc', tag: '3' }, { pat: '111', res: 'cej', tag: '4' }, { pat: '222', res: 'qwd', tag: '5' }, { pat: '222', res: 'asd', tag: '6' }, ] const val = [] arrayPat.forEach((curr) => { let newPath = val.find(currentItem => currentItem.pat === curr.pat); if (!newPath) { val.push({ pat: curr.pat, res: [curr.res], tag: curr.tag }) } else { newPath.res.push(curr.res) } }); console.log(val)

You may need array.reduce instead of filter. Secondly the required value of tag is not clear from the question. You can modify this answer to set proper value of tag

 const arrayPat = [{ pat: '111', res: 'qwe', tag: '1' }, { pat: '111', res: 'sda', tag: '2' }, { pat: '111', res: 'xzc', tag: '3' }, { pat: '111', res: 'cej', tag: '4' }, { pat: '222', res: 'qwd', tag: '5' }, { pat: '222', res: 'asd', tag: '6' }, ] const val = arrayPat.reduce((acc, curr) => { if (!acc[curr.pat]) { acc[curr.pat] = { pat: curr.pat, res: [curr.res], tag: curr.tag } } else { acc[curr.pat].res.push(curr.res) } return acc; }, {}); console.log(Object.values(val))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM