我试图弄清楚如何将字符串更改为对象。然后,我要获取该对象并将其插入数组,还要从数组中删除字符串。有关如何执行此操作的任何想法?到目前为止,我通过数组获取映射的字符串。
searchTerms.map(term => {
if(term.length > 25) {
const trimmedSearchTerm = term.substring(0,25) + '...';
const obj = {
value: term,
trimmedValue: trimmedSearchTerm,
icon: 'search',
removable: true,
};
return searchTerms.push(obj);
} else if(term === "Last 500"){
const obj = {
value: term,
trimmedValue: term,
icon: 'date_range',
removable: false,
}
return searchTerms.push(obj)
} else {
term = {
value: term,
trimmedValue: term,
icon: 'search',
removable: true,
}
}
});
答案 0 :(得分:1)
我相信您只是忘了返回每个条件的值。这是一个有效的例子
let searchTerms = ["test1", "1234567891011121314151617181920", "Last 500"]
const mappedTerms = searchTerms.map(term => {
let mappedTerm;
if(term.length > 25) {
const trimmedSearchTerm = term.substring(0,25) + '...';
mappedTerm = {
value: term,
trimmedValue: trimmedSearchTerm,
icon: 'search',
removable: true,
};
} else if(term === "Last 500"){
mappedTerm = {
value: term,
trimmedValue: term,
icon: 'date_range',
removable: false,
}
} else {
mappedTerm = {
value: term,
trimmedValue: term,
icon: 'search',
removable: true,
}
}
return mappedTerm;
});
console.log(mappedTerms);