如何使用下划线.js编辑具有字符串键值对的对象数组中的字符串

How do you use underscore.js to edit a string in an array of objects that have a string key value pair?

本文关键字:字符串 键值对 数组 对象 下划线 何使用 js 编辑      更新时间:2023-09-26

如果可能的话,我更喜欢下划线解决方案,但如果这是我能得到的最好的解决方案,我会采用香草 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 = [{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)