Home > Blockchain >  Is there a way to iterate through a commma seperated list and a create a new list with single entrie
Is there a way to iterate through a commma seperated list and a create a new list with single entrie

Time:10-04

I've got an array list like this :

| serialNumbers   |  Date      |
| --------------- | ---------- |
| 543545, 235524  | 2022/07/23 |
| 213422          | 2022/10/11 |
| 342404, 324352  | 2021/08/03 |
| 213422          | 2022/10/11 |

How do I create a list like this where entries with multiple serial numbers are seperated into their own entries in javascript or SQL? I'm getting the data from sql into react so is there any way in either sql or JS to do that? I know there is .split() method in JS but I'm not sure how to implement it with this array

expected result:

| serialNumbers   |  Date      |
| --------------- | ---------- |
| 543545          | 2022/07/23 |
| 235524          | 2022/07/23 |
| 213422          | 2022/10/11 |
| 324352          | 2021/08/03 |
| 324352          | 2021/08/03 |
| 213422          | 2022/10/11 |

CodePudding user response:

In Javascript you can use reduce() to do it,waiting for a solution using map() to do it

const arr =[
    {
      "serialNumbers": "543545, 235524",
      "Date": '2022/07/23'
    },
    {
      "serialNumbers": "213422",
      "Date": '2022/10/11'
    },
    {
      "serialNumbers": "342404, 324352",
      "Date": '2021/08/03'
    },
    {
      "serialNumbers": "213422",
      "Date": '2022/10/11 '
    }
]


const res = arr.reduce((acc,val) =>{
  let nums = val.serialNumbers.split(",")
  for(num of nums){
   acc.push({"serialNumbers":num.trim(),"Date":val.Date})
   }
  return acc
},[]);

console.log(res)

  • Related