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

216
Visualizações
if value contains string+number in array of objects

I have an array like this:

array[
{name:test},
{name:test1},
{name:test2}
]

I have the str and n variables

let str = 'test';
let n = 1;

let obj = array.some(o => o.name.includes(str + n));
//check if string exist in array + n

if (obj === true) ++n
else str += n
 
console.log(str) // 'test'

the idea is that I want to check if string(test) exist in array of objects, if it exists I should add number, if it does not exist, then I should not add number

what i should get: 
if let str = "test" - console.log(str) // 'test3'
if let str = "test2" - console.log(str) // 'test2_1'

I just try to use:

  for (i = 0; i < array.length; i++) {
              let obj = array[i].name.includes(str + n)
                while (obj === true) n++
                str += n
      }
console.log(str) // test111
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use .filter()

let array = [
    {name:'test'},
    {name:'test1'},
    {name:'test2'}
];
let str = 'test', currentStr = 'test';
let n = 1;

if (array.filter((item) => item.name === str).length) {
    currentStr = str + n++;
}

while (array.filter((item) => item.name === currentStr).length) {
    currentStr = str + n++;
}
 
console.log(currentStr);

about 4 years ago · Juan Pablo Isaza Relatório

0

function placeHolder(arg) {
    for (let i = 0; i < arg.length; i++) {
        if(parseInt(arg[i].name.slice(-1))) {
            continue;
        } else {
            arg[i].name = arg[i].name + (i + 1) 
        }
    }

    return arg;
}
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