-3

i have an object like this

{make: 'Audi,BMW,Cadillac', model: 'RDX,Mop,Rvn'}

What to convert it to this

{make: ['Audi','BMW','Cadillac'], model: ['RDX','Mop','Rvn']}
  • 2
    Are you definitely after arrays with _one_ element in them and not multiple (eg: `['Audi', 'BMW', 'Cadillac']` instead of `['Audi,BMW,Cadillac']`)? What have you tried so far to achieve this / what are you struggling with? – Nick Parsons Oct 02 '21 at 10:09
  • Does this answer your question? [How can I convert a comma-separated string to an array?](https://stackoverflow.com/questions/2858121/how-can-i-convert-a-comma-separated-string-to-an-array) – Anurag Srivastava Oct 02 '21 at 10:09

3 Answers3

1

The Object.entries and Object.fromEntries functions handles this case well.

const data = {make: 'Audi,BMW,Cadillac', model: 'RDX,Mop,Rvn'};

const dataWithArrays = Object.fromEntries(
    Object.entries(data)
        .map(([key, value]) => [key, value.split(',')])
);

console.log(dataWithArrays);
0

This is what you need

obj.make = obj.make.split(",")

obj.model = obj.model.split(",")

SoGoddamnUgly
  • 706
  • 4
  • 9
0

Simple any easy, using Object.keys, Array.reduce and String.split

const data = {make: 'Audi,BMW,Cadillac', model: 'RDX,Mop,Rvn'};

const res = Object.keys(data)
   .reduce((acc, k) => (acc[k] = data[k].split(','), acc), {})

console.log(res);
navnath
  • 3,548
  • 1
  • 11
  • 19