Exclude a variety of keys using wildcards or regex when conducting comparisons

How can I exclude certain properties in a JSON object that contain specific characters?

var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}
var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}

Now, I want to remove all properties that contain the string foo.

var result = _.isEqual(
  _.omit(obj1, ['\*foo\*']),
  _.omit(obj2, ['\*foo\*'])
);

Is there a way to achieve this? Any suggestions would be appreciated.

Answer №1

When working with vanilla JS, there are various approaches you can take to achieve a certain result.

One technique involves filtering keys that contain specific values like 'foo'; then extracting the key-value pairs from the original array based on these filtered keys; finally, combining them into a final object.

  1. Filter out keys containing 'foo' using the Object.keys() method
  2. Map over the filtered keys to create an array of objects with the key-value pairs
  3. Combine the objects using Object.assign() to form a new object

var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}
var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""};

var o = Object.keys(obj1).filter(o=> !o.includes('foo')),
    i = o.map(i=> ({[i] : obj1[i]})),
    obj =  Object.assign({}, ...i);
    console.log(obj)

Answer №2

To exclude certain keys, you can provide a function as an argument to omit method with the key as the second parameter:

const updatedObject = _.omit(originalObject, (value, key) => key.includes('bar'))

Answer №3

Here is a method you can use to manipulate an object:

function removeProps (obj, prop) {
  Object.keys(obj).forEach((key) => {
    if(key.indexOf(prop) !== -1) delete obj[key];
  });
}
var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""};

removeProps(obj1, "foo");
console.log(obj1);

If you want to keep the original object intact, you can do this:

function removeProps (obj, prop) {
  obj = JSON.parse(JSON.stringify(obj));
  Object.keys(obj).forEach((key) => {
    if(key.indexOf(prop) !== -1) delete obj[key];
  });
  return obj;
}
var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""};

var obj1Updated = removeProps(obj1, "foo");
console.log(obj1);
console.log(obj1Updated);

Answer №4

In response to your request for a solution using regex, here is the code snippet:

const person1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}
const person2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""};

Object.prototype.filterRegex = function(regex) {
    let filteredKeys = Object.keys(this).filter((key) => !regex.test(key));
    return filteredKeys.reduce((result, key) => {
        result[key] = this[key];
        return result;
    }, {});
};

person1.filterRegex(/foo/);
person2.filterRegex(/foo/);

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

The call is not being answered by the server route (NodeJS + express)

I have encountered an issue while setting up a server using NodeJS and Express. When I attempt to make a get request to the basic route ('http://localhost:3000/'), the request seems to hang indefinitely. Despite thoroughly reviewing my code multi ...

Using AJAX in PHP to submit checkbox values in a form without reloading the page

Recently, I delved into learning ajax and found it to be truly amazing and a major time-saver. However, I encountered a roadblock when attempting to send form data without having the page reload. Here is an excerpt of my HTML code. <form id="form ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

Error: Unable to locate image module in REACT

Trying to troubleshoot image loading in a React project. Currently testing with an individual image, but plan to eventually store multiple images in an array for easier management. However, I'm encountering an issue where the image won't load and ...

The JSON response generated by the C# ServiceContract is not quite what I was anticipating

Currently, I am utilizing a service contract as an API with a particular interface declaration: namespace MyAPI { [ServiceContract(Namespace = "http://MyAPI")] public interface IMyAPI { [OperationContract] [WebInvoke(Method = " ...

Unable to insert hyperlinks into table rows within a React application

A React function was created by me to display a table. This is how the table appears. It accepts JSON as a parameter: { "id": 1, "firstName": "Richard", "lastName": "Morrison", "number ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

Using NextJS to pass a parameter to an onClick function

I've been using the react-simple-star-rating package in this sample code. However, I'm facing an issue: Within my trains parameter, there is a variable id that I would like to pass to the handleRating function using onClick, but I can't see ...

Struggling to fetch the latest state value in React with hooks?

I have implemented functional components with 2 radio buttons and a submit button. However, upon clicking the submit button, I am unable to retrieve the updated value properly. Check out my code at this link. To reproduce the issue: Start the applicatio ...

There seems to be a mysterious absence of chuck norris jokes in

I'm attempting to call two different APIs by clicking a button to display a random joke on the screen. I've created two separate functions to fetch the APIs and used Math.random() to generate a random number. If the number is greater than 50, one ...

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...

Unity Save Load System: Harnessing Application.persistentDataPath

As a beginner Unity developer, I successfully implemented a Save & Load function using an asset that supports storage. Typically, the data is saved as a Json file in the Application.persistentDataPath/ folder. However, I encountered an issue where the fun ...

Looking for a way to create a regular expression that can parse an email response containing the newline character?

Do you need help parsing only the most recent reply from the email thread below? For example, Hello Nikhil Bopora,↵↵Just to give a brief, I am in process of building an alternate e-lending↵platform. I tried using the general regex /[\s]*([&bsol ...

Tips for executing specific javascript on small screens or mobile devices

I am currently in the process of developing a Vue web application that needs to be functional on all devices. I have certain code that should only run on small screens or mobile devices. Right now, I am using an if statement with $(window).width() to achie ...

Is it possible to iterate over an enum using Object.entries<T>(Enum).map() in TypeScript, or does it only function with string-based enums?

Currently, I am in the process of developing a react form that requires users to select options related to a job. These options are represented by enums, with some being string-based and others number-based. For instance, here is an example of a string-ba ...

Issue with hidden input field not displaying array on submission

I need assistance with adding filenames that have been uploaded to an array in a hidden input field within a form. Here's what I currently have in my form: <input type="hidden" name="myFiles[]" id="myFiles" value=""> This is how my file upload ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

How can JavaScript automatically calculate the sum of various numbers entered into multiple input fields?

I would like to automatically add different numbers entered in multiple input fields using JavaScript. Is there a way to calculate the sum of numbers entered in various input fields using JavaScript? "The input field consists of n numbers..." and I am ut ...