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

115
Visualizações
JavaScript: Dynamically build a condition by fetching properties/values of an array with one object

I am trying to make a script which

  1. Gets the current URL (url1 variable in the example) which contains params/values and which can be entirely different each time - OK
  2. I extract both params and values and create an object from them with keys/values - OK
  3. I build a condition for later use, dynamically which does not expect a certain number of pairs, so it gets built from whatever it finds in the object - NOT OK

.

let url1 = 'http://localhost/myproject/results?id=0001&area=eiffel+tower&city=Paris&whatever=else';

function URLToArray(url) {
    var request = {};
    var pairs = url.substring(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < pairs.length; i++) {
        if(!pairs[i])
            continue;
        var pair = pairs[i].split('=');
        request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
     }
     console.log(request); // { id: '0001', area: 'eiffel+tower', city: 'Paris', whatever: 'else' }
     return(request);
}

let paramsObj = URLToArray(url1);

console.log(paramsObj)  // { id: '0001', area: 'eiffel+tower', city: 'Paris', whatever: 'else' }

// Step 3 below, where the issue is and I expect
// id === '0001' && area === 'eiffel+tower' && city === 'Paris' && something === 'else'

paramsObj.forEach((item) => {
  let condition = '';
  let keys = Object.keys(item);
  keys.map((k) => {
    if (condition) {
      condition += ` && ${k} === '${item[k]}'`
} else {
  condition = `${k} === '${item[k]}'`
    }

  })
  console.log(condition);
})

Outputs

paramsObj.forEach((item) => { TypeError: paramsObj.forEach is not a function at Object.<anonymous>

Expected on console.log(condition)

id === '0001' && area === 'eiffel+tower' && city === 'Paris' && whatever === 'else'

Note: if the object was inside [ ] brackets, the output would somehow be the expected one. However URLToArray(url) outputs object without brackets.

almost 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

ForEach method is an array method and you're trying to use it on an object, you should probably just create a function that takes in an object as one of its parameters.

function ProcessItem(item) {
  let condition = '';
  let keys = Object.keys(item);
  keys.map((k) => {
    if (condition) {
      condition += ` && ${k} === '${item[k]}'`
    } else {
      condition = `${k} === '${item[k]}'`
    }

  })
  console.log(condition);
}

almost 4 years ago · Santiago Trujillo Relatório

0

Consider the following.

var url1 = 'http://localhost/myproject/results?id=0001&area=eiffel%20tower&city=Paris&whatever=else';

function getQueryFromURL(u) {
  var r = {};
  var parts;
  if (u.indexOf("?") > -1) {
    parts = u.substr(u.indexOf("?") + 1).split("&");
    $.each(parts, function(i, v) {
      r[v.split("=")[0]] = decodeURI(v.split("=")[1]);
    });
  }
  return r;
}

function objJoin(o, a, b) {
  var r = "";
  var arr;
  $.each(o, function(k, v) {
    if (r.length == 0) {
      r += [k, a, v].join(" ");
    } else {
      r += " " + [b, k, a, v].join(" ");
    }
  });
  return r;
}

let paramsObj = getQueryFromURL(url1);

console.log(paramsObj);

console.log(objJoin(paramsObj, "===", "&&"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This does not do anything vastly different, it just makes a bit better use of the tools at hand to get the same result.

almost 4 years ago · Santiago Trujillo Relatório

0

The URLToArray() returns an object and not an array. You cannot use forEach on an instance of an object.

Instead, you may want to iterate over keys, like the following:

Object.keys(paramsObj).forEach((key) => {
  const value = paramsObj[key];
  let condition = '';
  if (condition) {
    condition += ` && ${key} == ${value}`;
  } else {
    condition = `${key} == ${value}`;
  }
);
almost 4 years ago · Santiago Trujillo 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