Home > Software engineering >  need to convert object to JSON value
need to convert object to JSON value

Time:10-10

I have following request body,

{
    name1:"john,doe",
    name2:"peter,frank"
}

I need to get output as following

{
    "name1":["john","doe"],
    "name2":["peter","frank"],
}

I am trying to use array methods.

CodePudding user response:

Iterate over the object with for...in, and split the value into an array. Then JSON.stringify the object.

const res = {
  name1:"john,doe",
  name2:"peter,frank"
};

for (const key in res) {
  res[key] = res[key].split(',');
}

console.log(JSON.stringify(res));

CodePudding user response:

You can use Object.entries() and iterate over every key value and convert value into array and get back the new object using Object.fromEntries().

const o = { name1: "john,doe", name2: "peter,frank" },
      result = Object.fromEntries(Object
        .entries(o)
        .map(([key, val]) => ([key, val.split(',')]))
      );
console.log(result);

  • Related