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

[
  {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)

Leave a Reply