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

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

Why is it that PowerShell cannot execute Angular commands?

Recently, I started diving into Angular and encountered an issue using PowerShell in Windows. Every time I run an angular command like: ng new new-app or ng serve I keep getting this error message: ng : File C:\Users\< username >\ ...

Making a dropdown menu spin using Jquery and Javascript

I am in need of a unique solution for a dropdown menu that appears rotated 90 degrees anticlockwise. The goal is to have the dropdown select "button" text displayed vertically, with the options sliding out in a similarly rotated, sideways manner featuring ...

Get rid of any empty space in the image preview icon

Is there a way to eliminate the white space that appears when mixing landscape and portrait images? I want the images to move up and fill the space, even if they don't align perfectly. Additionally, I would like the images to resize based on the scal ...

Safari not updating Angular ng-style properly

I created a simple carousel using Angular and CSS animations which works well in Chrome. However, I recently tested it in Safari and noticed that the click and drag functionality does not work. I've been trying to fix this issue for days and could use ...

Verifying One Time Password (OTP) from MSG91 URL using ReactJS

Currently, I am working on a small project that involves receiving and verifying OTPs from MSG91. While I have managed to successfully receive OTPs using MSG91, I am encountering an issue when trying to verify OTPs - specifically, I keep getting an error ...

I am interested in monitoring for any alterations to the @input Object

I've been attempting to detect any changes on the 'draft' Object within the parent component, however ngOnChange() does not seem to be triggering. I have included my code below, but it doesn't even reach the debugger: @Input() draft: ...

Achieving a transparent background in WebGLRender: A guide

I've been experimenting with placing objects in front of CSS3DObjects using the THREE.NoBlending hack. However, in the latest revisions (tested on r65 and r66), I only see the black plane without the CSS3DObject. Here is a small example I created: in ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Issues with implementing Rails 4 with jQuery, javascript, and coffee scripts causing functionality to malfunction

Although I have nearly two decades of experience in C/C++ for control systems and firmware, as well as proficiency in shell and perl scripting, I am new to rails and web development. Despite including jquery in the application.js manifest, I am unable to ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...

adjust time in jQuery AJAX request when a button is clicked

I have the following code snippet that triggers when a button is clicked. When a user clicks on a button, I want to show a progress bar or waiting image in the browser for 5 seconds. How can I set a timeout and display the progress bar or waiting image wh ...

Retrieving data from the setlist FM API

Greetings, I am currently working on a project using Vue and Bootstrap to create a grateful dead website. The idea is to allow users to search by year to display setlists, with a limit of 5 setlists per page that can be scrolled through. However, I have h ...

Ways to activate a function upon validation of an email input type

Within my HTML form, there is an input type="email" field that requires a valid email pattern for acceptance. I am attempting to send an AJAX request to the server to confirm whether the entered email already exists in the database after it has been verif ...

When attempting to add an item to an array within a sub-document using Mongoose and MongoDB, the error message "Property 'messages' not found" is returned

I am working with four different models: teacher, student, teacherMessageSchema, and studentMessageSchema. The teacherMessageSchema is a subdocument within the 'teacher' model under the messages: [teacherMessageSchema] property, while the student ...

Fade out the notification div when the user clicks anywhere outside of it

I am currently working on a website with a notification feature. When the user clicks on the notification button, a notification box will appear at the bottom of the button. I would like the behavior of this notification to be similar to Facebook's - ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows: try { const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, { headers: { Accept: 'application/json', 'C ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...