Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
How to add to URL?

I am creating a filtering functionality and I would like to add the selected filters to the url for navigation purposes. Here is an array of objects:

let arr = [
{available:true},
{variantOption:{name:"size",value:"2XL"}},
{productType:"Apparel"}
]

I need it in the following format which I think are according to the W3c guidelines:

www.whatever.com/collection?available=true&productType=apparel&somethingElse=something etc

I am not able to figure out how to add something like variantOption key and values to the url in format like so. So that when I retrieve the values from the URL, they end up in the same format like the original array of objects was, which I want to use for the api call.

I would be using window.history.pushState for this use case here.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You will need to loop through the array.

for (let item of arr) {

then you will need to get each key of the object (item).

for (let key in item)

because one of them is another object you will need to check if the value is object

if (typeof item[key] === "object")

if true,

you need to loop one more time to get the extra key value pairs and pass them to the url as params..

for (let innerKey in item[key]) {

newLink.searchParams.set(innerKey, item[key][innerKey]);

else,

just take the key and value and pass them to the url as params.

newLink.searchParams.set(key, item[key]);


the loop at the end should look like this:

const newLink = new URL(window.location.href); // here you  can put any base url
for (let item of arr) {
  for (let key in item) {
    if (typeof item[key] === "object") {
      for (let innerKey in item[key]) {
        newLink.searchParams.set(innerKey, item[key][innerKey]);
      }
    } else {
      newLink.searchParams.set(key, item[key]);
    }
  }
}

and then to use the newLink.href as the url. you mentioned that you want to use window.history.pushState . so you can call the function and pass the url as argument.

example here: codesandbox example

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda