Execute a skip function on the source object

I'm completely new to using underscore js, and I'm attempting to exclude a specific property from an Object. What I tried was

myObj = _.omit(myObj,name)
console.log(myObj);

However, the myObj still retains the property name. Interestingly, if I do this it appears to work:

newMyObj= _.omit(myObj,name) 
console.log (newMyObj) 

it seemed to work fine. Am I making a mistake somewhere? Can someone offer any help? Here's how the myObj is structured:

Angola: "4.134137685",Brunei: "2.532726835",Countries: "2004",Croatia: "1.717672961", keys: Array[11]

I am aiming to omit "keys," which happens to be an array of objects.

Thank you

Answer №1

If you're not familiar with debuggers, it's time to make them your best friends. Take a moment to understand what they are and how they can help you in your coding journey. Look up resources like "Chrome devtools" on Google and start using breakpoints before calling _.omit. Dive into the console by typing myObj and name to examine their contents, or utilize the 'Scope Variables' section for a deeper analysis. Take a single step (F10) and observe any changes in variables, or recheck the value of myObj in the console.

In your case, you've noticed that property deletion works fine with newMyObj= _.omit(myObj,name), but not with myObj= _.omit(myObj,name). This behavior is puzzling and hints at underlying factors you're overlooking. Perhaps there's more to the story, like this example:

myObj = { keys: [] };
name = "keys";
delete_property();
console.log(myObj.keys); // []

function delete_property(myObj) {
    myObj = _.omit (myObj, name);
}

This setup doesn't function as expected because the assignment within the function merely alters the argument's value without affecting the external myObj. For a comprehensive solution, share more of your code for further insights. Nonetheless, tackling such debugging challenges is an integral part of becoming a seasoned programmer, so embrace the troubleshooting process with curiosity and enthusiasm.

Answer №2

My understanding of this question is that you are looking to eliminate a property from an object using the omit() method. It's important to note that omit() creates a new copy of the object without the specified property, without modifying the original object.

Based on this context, the code provided below, which aligns with your current implementation, functions correctly:

var copy,
    obj = {
        Angola: "4.134137685",
        Brunei: "2.532726835",
        Countries: "2004",
        Croatia: "1.717672961", 
        keys: Array[11]
    },
    check = function (o) {
        _.each(o, function (value, key) {
            console.log("key: " + key + " value: " + value);
        });
    };


copy = _.omit(obj, "keys");
check(copy);

obj = _.omit(obj, "keys");
check(obj);

Whether you assign the result to a new variable or update the existing one, the output remains consistent.

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

Having trouble with Vuex in Vue JS when trying to set up a modular store

Currently, I am in the process of building a web application using Vue along with Vuex. Despite being new to Vue, I am attempting to integrate Vuex into my Vue application. However, I am encountering an issue when using modularised Vuex. In my project, th ...

Efficiency levels of reach = within angular instructions

Creating a directive can be done in various ways. Here is an example of how I structured mine: 'use strict'; myApp.directive('mySwitchOnOff', [ '$rootScope', function($rootScope) { return { restrict: 'C' ...

Progress tracking for async route guards in Vue router

Using async tasks in my router's navigation guard: router.beforeEach((to, from, next) => { somethingAsync().done(next) }) I am wondering if the router provides any indication for when it is currently "loading," or if I need to manage this mysel ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Error: Access Denied (CSRF token not found or invalid) - despite being present

Despite including a csrf_token, I keep experiencing the error mentioned above. I have successfully used the same csrfmiddlewaretoken for my other ajax calls without any issues, but for some reason, I'm encountering a forbidden error in this case. Any ...

What is the best way to share a variable from a component in Vue.js?

As I develop a validation component for publication, my goal is to leverage a variable similar to this.$validate.bla(), with "bla" representing a function within my component. ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Limit not reached by substring function

When the character limit exceeds 20 characters, the substring function extracts the first 20 characters typed in the input. It replaces any additional characters that are entered after reaching the max limit of 20. In my program, however, I am able to con ...

Limit on the number of users for organizations

Creating a website that connects users to organizations, where users can request to join an organization that has a 500 people limit. However, the function is not working correctly as it fails to check if the current number of users (current_users) is less ...

Challenges with Validating Bootstrap Datepicker Functionality

I need to restrict the datepicker input control to only allow selection of dates from the current date onwards. Despite trying to implement validation using the bootstrap-datepicker library and the following JavaScript code, I am still facing issues: $(& ...

encountering challenges while creating a multi-step registration form with Node.js, Express, and mongoDB

I'm currently working on a 3-page registration form that saves data using MongoDB. However, I encountered an issue where the collection "detail" only stores one user's data at a time due to the structure of my post requests across all pages. I ne ...

Is using setTimeout in a group of promises blocking in JavaScript?

Is it possible for multiple requests to be queued up and executed in sequence when calling the function func? The third promise within func includes a lengthy setTimeout that can run for as long as 3 days. Will additional calls to func trigger one after an ...

Troubleshooting problem with displaying circular tag image below an image using Jquery

I'm looking to enhance my HTML DOM by adding circular tag images with dimensions of 25x25 pixels to all image tags. While my current method is functional, I've noticed that the position sometimes shifts and the tag often ends up displayed below t ...

Middleware designed for logging in React, akin to Multer in the realm of Express JS

Currently developing a React application that involves multiple API calls. I am exploring the possibility of integrating a middleware to intercept and log all these calls, similar to how Multer functions in an Express server. I am also curious if there is ...

Vue.js Human Time Component Overwhelms CPU Usage

This specific component is designed to convert a timestamp into relative time text: Vue.component('human-time', { props: ['time'], methods: { format(time){ const formats = [ [60, 'seconds', 1], [ ...

Utilize buttons to send data to a PHP script

Currently, I am in the process of developing a control panel for an application, consisting of an array of buttons. My aim is to relay information about the specific button pressed to the designated script responsible for executing commands. However, I am ...

NextJS Input Field causing a strange "Hydration Error indicating server HTML should not contain a <div> within a <form>", perplexingly occurring only in Chrome and exclusively on my personal computer

Looking for some assistance with a website I'm working on using NextJS and TailwindCSS. There seems to be a pesky little issue in my code that's causing some trouble. Below is the code snippet for the MainContent section of the page: "use c ...

Retrieving dynamically created row from code-behind

My ASPX page contains a table with headings. I am dynamically adding rows to the table using JavaScript, but when trying to access these newly added rows on the server side, I can only see the heading row and not the new ones. The table always appears to h ...

A curious phenomenon observed in the behavior of the jQuery offset() method

Once I executed the following code snippet multiple times: $view.offset({ left : X, //X remains constant top : this.y }); console.log($view.offset()); //displays expected output I noticed (using Firebug) that the HTML code looked like this: <di ...

Navigating through the sidebar on Next.js

I am currently exploring how to utilize next.js routes for dynamically populating a sidebar component with route instructions. The goal is to have the main div display the relevant component when a sidebar option is clicked. While I've come across tu ...