Home > Software design >  Converting Array stored as a String to a List object in JavaString
Converting Array stored as a String to a List object in JavaString

Time:09-23

I have the following list:

nested_list = [
  ["[63]"],
  ["[61]"],
  ["[7]"],
  ["[63]"],
  ["[80, 18]"],
  ["[80, 43, 18, 20]"]
]

Which is a mess I know, but this is the data that I have to deal with at the moment and I need it to be like this:

[63, 61, 7, 63, 80, 18, 80, 43, 18, 20]

So basically converting it into a list of numbers. Is this doable using as minimum loops as possible?

I have used flat() nested_list .flat(2) and ended up with the following result:

[ '[63]', '[61]', '[7]', '[63]', '[80, 18]', '[80, 43, 18, 20]' ]

Also tried reduce concat following this but since it is a string, it is not working and I'm not sure where to go from here.

CodePudding user response:

.flatMap() JSON.parse() can do this quite easily

const nested_list = [
  ["[63]"],
  ["[61]"],
  ["[7]"],
  ["[63]"],
  ["[80, 18]"],
  ["[80, 43, 18, 20]"]
];

const result = nested_list.flatMap(JSON.parse);

console.log(result)

  • Related