Add comma values if the key is equal

Asked

Viewed 39 times

0

How to format an array like this...

[
{name: "city", value: "sao-paulo-sp"},
{name: "types-properties", value: "apartamento"},
{name: "types-properties", value: "casa"}
]

to arrive at this result.

[
{name: "city", value: "sao-paulo-sp"},
{name: "types-properties", value: "apartamento,casa"}
]

This data is pulled from a form and formatted with .serializeArray()

At first, I thought I’d make a .map(), compare the key and if it existed in the array I gave a .push(), add the values with a comma.

I tested it this way here, but the URL is empty or null, so no list.

1 answer

3


There are several ways to do this... if the name is the only key you can make an object and concatenate the value in value of key name.

Something like that:

const array = [{
    name: "city",
    value: "sao-paulo-sp"
  },
  {
    name: "types-properties",
    value: "apartamento"
  },
  {
    name: "types-properties",
    value: "casa"
  }
];

const obj = array.reduce((obj, entry) => {

  if (!obj[entry.name]) obj[entry.name] = [];
  obj[entry.name].push(entry.value);
  return obj;
}, {});

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

// dá 
//  {
//    "city":["sao-paulo-sp"],
//    "types-properties":["apartamento","casa"]
//  }

It’s quite possible that’s what you need. If you really want the format you refer to you can take one more step, now that you have everything organized and do:

const arrayOrganizada = Object.keys(obj).map(name => {
  return {
    name: name,
    value: obj[name].join(',')
  }
});

Everything together would be like this:

const array = [{
    name: "city",
    value: "sao-paulo-sp"
  },
  {
    name: "types-properties",
    value: "apartamento"
  },
  {
    name: "types-properties",
    value: "casa"
  }
];

const obj = array.reduce((obj, entry) => {

  if (!obj[entry.name]) obj[entry.name] = [];
  obj[entry.name].push(entry.value);
  return obj;
}, {});

const arrayOrganizada = Object.keys(obj).map(name => {
  return {
    name: name,
    value: obj[name].join(',')
  }
});

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

// dá
//  [
//    {"name":"city","value":"sao-paulo-sp"},
//    {"name":"types-properties","value":"apartamento,casa"}
//  ]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.