Home > Back-end >  want to convert the values of data in an object to array
want to convert the values of data in an object to array

Time:10-02

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']}

CodePudding user response:

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);

CodePudding user response:

This is what you need

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

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

CodePudding user response:

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);

  • Related