如何使用 underscore.js 编辑具有字符串键值对的对象数组中的字符串?
How do you use underscore.js to edit a string in an array of objects that have a string key value pair?
如果可能的话,我更喜欢下划线解决方案,但如果这是我能得到的最好的解决方案,我会采用普通的 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)
如果可能的话,我更喜欢下划线解决方案,但如果这是我能得到的最好的解决方案,我会采用普通的 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)