1

i'm learning React and Javascript and i'd need to know the most elegant way to change a simple object into an array of objects (even if it only contain a single value). This object is itself contained inside an object. I'm neither a native english speaker nor a JS pro, so i'm aware that i'm probably not being very clear so i tried to set up the best example i could:

https://codesandbox.io/s/vibrant-kilby-1me4m?file=/src/App.js

(const queries are the datas as i get it at the moment, const desiredQueries is basically the hardcoded result of the solution i'm looking for, to see the error i'm getting atm, set the BREAK IT switch on. )

The object is created by Next router from query parameters, with the parameter as key and value as.. value.

When there is several occurrences of the same param (?role=guitarist&role=bassist, for ex), it will create an array of objects to store values, but when there is a single occurrence of a parameter (&type=person, for ex), it's creating a simple object.

And this is leading to issues when the data is later processed by a map function.

I could check if its an array or not at the map function level, and execute another function that is not trying to map the data if its not an array, but it would lead me to change a lot of code in several components and i feel like changing the initial object into an array is the best way to to it.

Thanks for your time!

1 Answer 1

1

If that's about looping through your object properties and forcing all the values into arrays, you may use the looping method of your choice and simply make use of Array.prtototype.concat(), like that:

const src = { role: ["guitarist", "bassist"], type: "person" },

      result = Object
        .keys(src)
        .reduce((acc, key) =>
          (acc[key] = [].concat(src[key]), acc), {})
          
console.log(result)          

But I'm not entirely sure whether extra looping through the source data to format it as you described is more elegant than looping just once upon rendering with .map() and choosing appropriate action conditionally based on value type.

Sign up to request clarification or add additional context in comments.

1 Comment

This is it ! Thanks a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.