gpt4 book ai didi

javascript - 如何使用 underscore.js 编辑具有字符串键值对的对象数组中的字符串?

转载 作者:行者123 更新时间:2023-12-03 07:53:13 24 4
gpt4 key购买 nike

如果可能的话,我更喜欢使用下划线解决方案,但如果这是我能得到的最好的解决方案,我会采用普通的 JS 解决方案。

我想使用数组 2 来编辑 array1 对象中以 array2 中的字符串开头或结尾的字符串。我正在寻找的结果可以在下面的 array3 的结果中看到:

array1 = [{key1: "Patty Bakery", key2: stuff}, {key1: "Bob Wine Shack",
key2: mattersNot}, {key1: "Romeo Clothing", key2: things}, {key1:
"StackIt", key2: finished}];

array2 = ["Patty", "Romeo", "Wine Shack"];

array3 = [{key1: "Bakery", key2: stuff}, {key1: "Bob",
key2: mattersNot}, {key1: "Clothing", key2: things}, {key1:
"StackIt", key2: finished}];

到目前为止,我能做的最好的事情就是使用以下代码删除 array1 中的整个对象:

array1.filter(function(a){
return!_.some(array2, function(b){
return startsWith(a.key1, b)})})
//I have installed and am using underscore.string

这给了我一个看起来像这样的 array3

array3 = [{key1:"StackIt", key2: finished}];

最佳答案

您可以使用 Regex 来表示以以下方式开头或结尾的模式。

以下是描述相同内容的片段

var array1 = [{
key1: "Patty Bakery",
key2: "stuff"
}, {
key1: "Bob Wine Shack",
key2: "mattersNot"
}, {
key1: "Romeo Clothing",
key2: "things"
}, {
key1: "StackIt",
key2: "finished"
}];

var array2 = ["Patty", "Romeo", "Wine Shack"];
var array3 = [];
array2.forEach(function(item) {

var startWithReg = new RegExp("^" + item);
var endsWithReg = new RegExp(item + "$");

console.log(startWithReg)

array3 = array1.map(function(row) {

row.key1 = row.key1.replace(startWithReg, '').trim();
row.key1 = row.key1.replace(endsWithReg, '').trim();
return row;

});
})

console.log(array3)

关于javascript - 如何使用 underscore.js 编辑具有字符串键值对的对象数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34923309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com