I prefer an underscore solution for this if possible but I'll take a vanilla JS solution if that is the best I can get.
I want to use array 2 to edit strings in the objects of array1 that start with or end with the strings in array2. The result I'm looking for can be seen in the results of array3 below:
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}];
So far the best I've been able to do is remove the whole object in array1 with this code:
array1.filter(function(a){
return!_.some(array2, function(b){
return startsWith(a.key1, b)})})
//I have installed and am using underscore.string
which gives me an array3 that looks like
array3 = [{key1:"StackIt", key2: finished}];
You can use Regex
for pattern starting with or ending with.
Following is a snippet depicting the same
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.