Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting an array of strings into an array of objects with key value pairs in javascript

I’m trying to convert the following array of strings string[] to an array of objects with the following format [{"title": value "value": value }]

This is the array I get

locationQuery = [
  "Antwerpen",
  "Hemiksem",
  "Antwerpenlei, Brasschaat",
  "Antwerpenplein, Gent",
  "Antwerpenstraat, Bredene",
  "Antwerpenstraat, Oostende",
  "'s-Herenstraat, Antwerpen",
  "'t Berkenveld, Antwerpen",
  "'t Doolhofje, Antwerpen",
  "'t Duivelshoekje, Antwerpen"
]

and this is the format I would like to convert it to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {title: "Antwerpen", value: "Antwerpen"},
  {title: "Hemiksem", value: "Hemiksem"},
  {title: "Antwerpenlei, Brasschaat", value: "Antwerpenlei, Brasschaat"}
  ...etc
]

Looking at other SO answers and I’m trying to use reduce, but I’m only getting the very last value from that array in {}.

For example when I do

      locationQuery.reduce(
        (a, v) => ({ ...a, ['title']: v, ['value']: v }),
        {},
      ),

I get the following: locationQuery {title: "'t Duivelshoekje, Antwerpen", value: "'t Duivelshoekje, Antwerpen"}

What I would like is the format:

locationQuery= [
  {title: "Antwerpen", value: "Antwerpen"},
  {title: "Hemiksem", value: "Hemiksem"},
  {title: "Antwerpenlei, Brasschaat", value: "Antwerpenlei, Brasschaat"}
  ...etc
]

>Solution :

You are returning an object and overload its title/values properties with new values. What you need is return an array and add a new object to it in every iteration:

const locationQueryArray = locationQuery.reduce(
    (previous, current) => [...previous, { title: current, value: current }], []
);
const locationQuery = [
  "Antwerpen",
  "Hemiksem",
  "Antwerpenlei, Brasschaat",
  "Antwerpenplein, Gent",
  "Antwerpenstraat, Bredene",
  "Antwerpenstraat, Oostende",
  "'s-Herenstraat, Antwerpen",
  "'t Berkenveld, Antwerpen",
  "'t Doolhofje, Antwerpen",
  "'t Duivelshoekje, Antwerpen"
];

const locationQueryArray = locationQuery.reduce(
  (previous, current) => [...previous, { title: current, value: current }], []
);

console.log(locationQueryArray)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading