Tengo una matriz como esta:
array[ {name:test}, {name:test1}, {name:test2} ]Tengo las variables str y n
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'la idea es que quiero verificar si existe una cadena (prueba) en una matriz de objetos, si existe, debo agregar un número, si no existe, entonces no debo agregar un número
what i should get: if let str = "test" - console.log(str) // 'test3' if let str = "test2" - console.log(str) // 'test2_1'Solo trato de usar:
for (i = 0; i < array.length; i++) { let obj = array[i].name.includes(str + n) while (obj === true) n++ str += n } console.log(str) // test111Puedes usar .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);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; }