Refine objects based on their properties without removing them from the dataset

I have a specific object structured as follows:

var myObj: {
    2:"None",
    20:"A",
    31:"A",
    32:"A",
    Social:"B",
    Method:"None"
}

My goal is to retrieve the object without the properties 'Social' and 'Method'.

Initially, I attempted to remove these properties within a computed property function, but it ended up deleting them from the main object entirely:

props: ['myObj']

computed: {
     filterOut: {
        var myObject = this.myObj
        delete myVar['Social'];
        delete myVar['Method'];

        return myObject
    }
}

Subsequently, I tried utilizing the filter method, only to encounter an error:

      var myObject = this.myObj.filter(key => {
          return key != 'Method' || key != 'Social'
      })

      return myObject

TypeError: this.myObj.filter is not a function

What would be the most effective approach to obtain the below object based on the initial one?

var myObj: {
    2:"None",
    20:"A",
    31:"A",
    32:"A"
}

Answer №1

To create a fresh object without those specific properties, you can follow these methods:

There is a promising proposal at stage 3 for rest/spread properties which allows you to achieve this easily:

const {Social, Method, ...newObj} = originalObj;

(Make sure to disregard the constants Social and Method.) Although it's currently just at stage 3, it is progressing towards stage 4 and has good chances of being included in ES2018; recent versions of both Chrome and Firefox support it without requiring special flags.

Keep in mind that this method only deals with own, enumerable properties.

In ES2015+, you have another option:

const newObj = {};
for (const key of Object.keys(originalObj)) {
    if (key != "Social" && key != "Method") {
        newObj[key] = originalObj[key];
    }
}

For those using ES5:

var newObj = {};
Object.keys(originalObj).forEach(function(key) {
    if (key != "Social" && key != "Method") {
        newObj[key] = originalObj[key];
    }
});

Both of these approaches also cover own, enumerable properties; if you require all own non-Symbol properties, consider using Object.getOwnPropertyNames.

Answer №2

To achieve the desired outcome, utilize Object.assign for creating a fresh object followed by removing unwanted properties.

const sampleObject = {
    2:"None",
    20:"A",
    31:"A",
    32:"A",
    Social:"B",
    Method:"None"
};

const newObject = Object.assign({}, sampleObject); // Alternatively, employ the spread operator {...sampleObject};

delete newObject.Social;
delete newObject.Method;

console.log(newObject);

Answer №3

If you're looking for a useful function, check out reduce.

Give this code a shot:

function removeProperty(obj, prop) {
  return Object.keys(obj).reduce((result, key) => {
    result = result || {};
    if (key !== prop) {
      return { ...result, [key]: obj[key] };
    }
    return result;
  })
}

You might find this helpful when working directly in the browser or wanting to avoid using babel. The following example has not been tested, whereas the previous one is thoroughly tested and part of my daily toolbox.

function removeProperty(obj, prop) {
  return Object.keys(obj).reduce((result, key) => {
    result = result || {};
    if (key !== prop) {
      return Object.assign(result, {[key]: obj[key]});
    }
    return result;
  })
}

Answer №4

Perhaps this versatile approach could provide a solution:

var obj = {
    2: "None",
    20: "A",
    31: "A",
    32: "A",
    Social: "B",
    Method: "None"
}

var filteredResult = _.pickBy(obj, (value, key) => _.toInteger(key))

console.log(filteredResult)
<script src="https://unpkg.com/lodash"></script>

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

Bringing in PeerJs to the NextJs framework

Currently delving into NextJs and working on creating an audio chat application, I've hit a roadblock while attempting to import PeerJs. An error message keeps popping up saying 'window is not defined'. import Peer from 'peerjs'; ...

Cursor opens up when the popup menu is activated

Could someone help me create a popup menu that behaves correctly? I am struggling to make it work as expected. Every time I try to hover over the menu, it disappears. I have already attempted various solutions but none seem to work. The menu should open an ...

Attempting to hash the password led to encountering an error

An issue was encountered: both data and salt arguments are required. This error occurred at line 137 in the bcrypt.js file within the node_modules directory. The code snippet below highlights where the problem is present: const router = require("express" ...

What could be causing the issue with this JS code?

var feedback = {}; feedback.data = ["Great!", "See ya", "Not a fan..."]; feedback.display = function() { this.data.forEach(function(item) { console.log(feedback.display()); }); } The goal here is to showcase the content stored within the ...

Oops! The Vue star rating encountered an error because it couldn't read the length property of an undefined value at line 26 of listToStyles.js

Encountering an issue with the getRating function in Vue while using the Vue-star-rating package in Laravel. Unsure of what the problem may be. getRating(){ var pathArray = location.pathname.split('/'); v ...

Express is throwing a TypeError because it is unable to access the property 'app', which is undefined

On my nodejs server running the express framework, I have been encountering a random error when making requests. The error occurs unpredictably, usually appearing on the first request and not on subsequent ones. It's challenging for me to identify the ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Display table rows that are hidden in an HTML/Angular toggle function

I am relatively new to Angular and I have a task of setting up a table. The dataset that I have is as follows:- data = [{rollno: 1,name: 'abc',subject: 'maths'}, {rollno: 4,name: 'xyz',subject: 'history'}, ...

Save information in a session using html and javascript

I'm having trouble accessing a session variable in my javascript code. I attempted to retrieve it directly but ran into issues. As an alternative, I tried storing the value in a hidden HTML input element, but I am unsure of how to properly do that wit ...

Dealing with HTML fields that share the same name in various positions can be tricky

Currently, I have developed a non-commercial web application using basic HTML, PHP, and Javascript along with Dynamic Drive's Tab Content code. This app serves as a tool for managing the books in my home library as well as on my ereader. My main goal ...

After activating the rewrite feature on Tomcat valve, JavaScript is loading twice

I've implemented the Tomcat rewrite valve in my single-page application to direct all requests, except for static resources, to my index.html file. Here is what my rewrite.config looks like: RewriteCond %{REQUEST_URI} (?!.*\.(?:jpg|png|css|js|js ...

Issue with filtering of values returned by functions

I've been working with Angular's currency filter and I've run into an issue. It doesn't seem to be filtering the data that is returned from a function. I have a feeling that I might be missing something, perhaps it has to do with how th ...

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Having trouble with Simplemodal showing link content in the modal window

Having trouble getting the modal window to display content from another link? I'm pretty sure I've connected them correctly using the right classes. This is the basic JavaScript provided by . jQuery(function ($) { // Load dialog on page load //$ ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

In Vue.js, I only want to retrieve and display the parent's ID or name once for each of its child components

<td v-if="currentId != loop.id" class="text-center"> <div :set="currentId = loop.id">{{ loop.id }}</div> </td> <td v-else></td> Looking to achieve a specific layout like this This invo ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

Cannot find JS variable after loop has completed

I am struggling to understand why the value of my variable is not changing in my function. Here is my code snippet: var count = function(datain){ let temparr = [], countobj = {}; $.each(datain, function(key, val) { console.log(temparr); cou ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

Utilize vue.js and spring-boot to seamlessly upload files utilizing axios

When working with a form that includes a text field and a file upload option, I encountered an issue. The file is named start.vue(say) and it triggers the module.js(say) file. This, in turn, calls service.js(say), which then executes the API in moveControl ...