在数组JS中更改许多字符串的资源密集程度较少
我试图改变很多字符串,但还没有找到一种“好”的方式。 我想做的是根据不同的标准删除一些字符串。 确切:
- 将'PD-111 S/A'更改为“ PD-111”<当字符串以'pd-
- 'change'kl.otherstuff'开头的所有实例“ s/a”的所有实例为'klotherstuff'&lt<删除所有“”实例。当字符串以“ kl”
- 更改'BD5000-50'开头时,到'bd5000'<删除所有“ -50”的实例,当字符串以'bd'开头时,
我尝试了.startswith()和.replace(),而没有任何运气和差异迭代器(例如.map)尝试创建一个函数以根据标准删除函数。
我最终做了一个foreach,但它的资源密集程度非常大(因为总的变化大约是4K字符串)。它有效,但真的很糟糕,我认为我是一个非常认真的菜鸟。
接下来,我将进行可重现的代码:
let firstArr = [{
sku: 'PD-123-A S/A',
stock: '0'
},
{
sku: 'PD-123-B S/A',
stock: '1'
},
{
sku: 'PD-123-C S/A',
stock: '1'
}
]
let repl = {
'PD-123-A S/A': 'PD-123-A',
'PD-123-B S/A': 'PD-123-B',
'PD-123-C S/A': 'PD-123-C',
}
firstArr.forEach(element => {
let keys = Object.keys(repl);
let values = Object.values(repl);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === element.sku) {
element.sku = values[i];
}
}
});
console.log(firstArr);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最可行的解决方案很可能是基于单个可重复使用的映射器函数,该函数获取Regex Lookup(字符串值的启动序列的键值对及其基于REGEX的替换模式)以
map
方法href =“ https://developer.mozilla.org/en-us/docs/web/javascript/reference/reference/global_obignts/array/array/map#parameters_in_in_detail” /a>。映射功能是一般实现的,因此对任何项目属性不可知。它操作所有原始物品的 ,以仅仅是字符串类型值执行替换,并创建最初处理项目的浅副本。因此,原始数据结构不会被突变。
以上实现的核心功能之一是基于查找的正则访问,该访问支持长度不同的键。下一个提供的测试代码演示了该解决方案的主要想法。
但是,如果OP只想映射现有的简单结构,例如提供的一个仅具有两个已知/固定属性的结构,则可以将上述通用解决方案归结为更有效的效率(“少资源密集” 用op的话)映射器实现...
The most viable solution most probably would be based on a single re-usable mapper function which gets the regex lookup (key-value pairs of a string value's start sequence and its regex based replacement pattern) passed as the
map
method's optional 2ndthisArg
parameter.The mapping function is implemented generically, thus agnostic to any item property. It operates all of an original item's
entries
, executes the replacement at just string type values and creates a sanitized shallow copy of the originally processed item. Thus the original data structure does not get mutated.One of the above implementation's core features is the lookup based regex access which supports keys of varying length. The next provided test code demonstrates this solution's main idea.
But in case the OP just wants to map over an existing simple structure like the provided one with only two known/fixated properties, the above generic solution can be boiled down into a much more efficient ("less resource intensive" with the OP's words) mapper implementation ...
我还不了解很多,但我没有尝试使用
.filter
和.map
做类似的事情,试图走更多.startswith()。替换(),但我真的无法使其起作用。
在尝试重现我无法做的事情的同时,我实际上做到了。
我仍然会发布答案,也许希望有一种更好的方法可以做到这一点。
解决的
I don't know much as of yet but I didn't try to use
.filter
and.map
to do something similar, trying to go more the route of.startsWith().replace()
but I can't really make it work.While trying to reproduce what I couldn't do, I actually did it.
I'll still post with the answer and maybe hope there's a better way to do this.
SOLVED