如何在不将对象转为字符串的前提下替换对象内所有匹配内容
实现方案
你只需遍历数组的每一项,对单个对象内的字符串属性单独做替换即可,全程不会涉及将整个users对象序列化转字符串的操作,符合你的约束要求。
示例代码
const targetLogin = 'kBr4pelyDy4yKVmiAAAD'; const matchStr = `data-login="${targetLogin}" data-status="online"`; const replaceStr = `data-login="${targetLogin}" data-status="gagged"`; // 遍历修改原数组 users.forEach(user => { user.fornonmods = user.fornonmods.replace(matchStr, replaceStr); user.formods = user.formods.replace(matchStr, replaceStr); });
如果需要保留原数组不做修改,可以用map返回新数组:
const newUsers = users.map(user => ({ ...user, fornonmods: user.fornonmods.replace(matchStr, replaceStr), formods: user.formods.replace(matchStr, replaceStr) }));
内容的提问来源于stack exchange,提问作者Cain Nuke
相关产品推荐
相关产品推荐

