What is the procedure for manipulating a string within an array of objects with a string key-value pair using underscore.js?

I am seeking a solution utilizing underscores, but I am open to a vanilla JS alternative if it proves to be the most effective option.

My goal is to utilize array 2 to modify strings in the objects of array1 that either start with or end with the strings found in array2. The desired result can be seen in the modified 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}];

Currently, the best I have achieved is removing the entire object from array1 using this code snippet:

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

This results in an array3 that resembles:

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

Answer №1

To identify patterns that start or end with certain characters, you can utilize the power of regular expressions (Regex).

Here's a code snippet demonstrating this concept:

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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to use a String as an index array key in Java? For example, can you do something like `array["a"] =

Is it possible for Java to utilize a String as an index array key? For instance: array["a"] = 1; ...

Trying to assign a property to an undefined variable inside a function

At the moment, I am configuring error messages on a login page for an extension using vue, and encountering issues within the importCreds() function. data(){ return { url:'', apikey:'', error:'', } }, meth ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

Asynchronous loading of HTML templates using JQuery/JavaScript

Currently, I am in the process of creating a webpage that includes code snippets loaded from txt files. The paths and locations of these txt files are stored in a json file. First, the json file is loaded in, and it looks something like this: [ {"root":"n ...

Ensuring the accuracy of forms using third-party verification services

While working on an Angular form validation using an external service, I encountered a cannot read property of undefined error. The component contains a simple form setup: this.myForm = this.fb.group({ username: ['', [this.validator.username] ...

Convert an array to UTF-8 encoding and extract the values into a text input field

Having encountered a minor issue, I've successfully moved data from one file to another using Ajax with the help of echo in my query. However, I'm now attempting to utilize json_encode(); and facing some difficulties. Could someone please point o ...

The Protractor option is nowhere to be found on the Run Configuration popup window in Eclipse

Issue with Protractor in Eclipse: Unable to locate Protractor option on Run Configuration popup. Despite following the steps outlined in http://www.protractortest.org/#/ and this guide on configuring Protractor with Eclipse (specifically the 2 Answer step ...

Compatibility Issue between Jquery UI CheckBox Button and Click Function in IE8

Situation: After calling addButton() function in jQuery, the checkbox element is successfully turning into a button. However, the click event that should trigger an alert message is not functioning. This issue seems to be specific to IE-8 compatibility. ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

Why is my jQuery clearQueue function malfunctioning?

I'm facing an issue with my AJAX function where multiple notifications are being displayed if the user calls it repeatedly in a short span of time. I want to show the notification only once and avoid queuing them up. AJAX FUNCTION function update(up ...

Using the DatePicker component with non-escaped Latin alphabet characters in date-fns for ReactJS

While attempting to integrate the DatePicker component from Material UI into my React project, I encountered an error. Although many attributed the issue to a version discrepancy, what ultimately resolved the problem for me was assigning a value to the Da ...

The server sends a response with a MIME type that is not for JavaScript, it is empty

I am trying to integrate an angular application with cordova. Upon running "cordova run android" and inspecting it in Chrome, the console displays the following message: "Failed to load module script: The server responded with a non-JavaScript MIME t ...

Styling of global checkbox focus in Material UI (applied globally, not locally)

Currently experimenting with customizing the styling of a checkbox when it is in focus globally using Material-UI (react). At present, only default and hover styles are taking effect: MuiCheckbox: { colorSecondary: { color: 'green', & ...

Improving List performance with React.cloneElement

I am uncertain about the usage of React.cloneElement within a List component. Is it recommended to avoid using it, especially when dealing with a large number of elements in the list? Does React.cloneElement cause unnecessary re-renders that can be optimal ...

Having trouble getting the jQuery on() method to work with the click event?

My jQuery code snippet is as follows: $(document).ready(function(){ $("div#overlay div#getFBid div#overlayClose").on("click", function(){ console.log("test") }); }); Additionally, here is the HTML code that is loaded using AJAX: <div ...

Hover Effect with CSS Selector - JavaScript or jQuery Implementation

I have a similar code snippet: <article class="leading-0"> <h2> <a href="link">link title</a> </h2> <ul class="actions"> <li class="print-icon"> <a ...><img...>& ...

Having trouble modifying the Input with split() in angularJS

I am faced with a nested JSON object that contains an array as one of its properties. Each item in the array is separated by a ';'. My goal is to use ';' as a delimiter to split each array item and make necessary changes. However, I am ...

assigning a value of undefined to the selected option in AngularJS

How can I use angularjs ng-options and ng-model directives to set the select option and detect when the dropdown option is selected or changed? I want to include an extra empty option so that the user can deselect it, and in that case, I want the value in ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

Adding data to a multidimensional array in JavaScript

I am in need of creating a multidimensional JavaScript array dynamically, following this specific structure: array_answers[0][1]:"yes" array_answers[1][2]:"no" array_answers[2][2-subquestion]:"text input" array_answers[3][8]:"yes" array_answers[4] ...