[英]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我有 str 和 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'
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
You can use .filter()
你可以使用
.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.