Home > Enterprise >  Convert an arrays of array surrounded by quotes into string array
Convert an arrays of array surrounded by quotes into string array

Time:05-06

I have date duration values in following format.

array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"], ...]';

And need to convert it as follows,

array2 = [ '2022-01-18 - 2022-01-21', '2022-02-15 - 2022-02-17', ... ]

For the work done I have followed two ways,

  1. formattedArray1 = array1.replace(/","/g, " - ").reduce((a, b) => a.concat(b), [])

this gives me an error:

array2.reduce is not a function

  1. formattedArray2 = [].concat.apply([], array1.replace(/","/g, " - ")); and this gives me the error

CreateListFromArrayLike called on non-object

To fix this any thought would be highly appreciated!

CodePudding user response:

What you've got there is an array serialised to JSON.

You can benchmark results

CodePudding user response:

array1 is stored as String, so you need to convert it to Array to use reduce or other array methods.

array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';
arr = JSON.parse(array1)
formattedArray1 = arr.map((e) => e.join(" - "))
// ['2022-01-18 - 2022-01-21', '2022-02-15 - 2022-02-17']

CodePudding user response:

  1. You are calling reduce on type string( array1.replace(/","/g, " - ") will return a string) , reduce works only with Array.prototype that's why you are getting reduce is not a function.

array2.reduce is not a function error.

You need to parse the array before doing reduce.

const array1 = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';
const parsedArr = JSON.parse(array1);
const result = parsedArr.map(date => date.join(" - ") )
console.log(result)

CodePudding user response:

Another Alternative

The transform could also be done at the same time the json is parsed by providing a reviver function that evaluates each key-value. if the value is a child array then join the elements.

let json = '[["2022-01-18","2022-01-21"],["2022-02-15","2022-02-17"]]';


let data = JSON.parse(json, (k,v) => k && v.push ? v.join(" - ") : v );


console.log(data);

  • Related