Keep only the selected properties in the object and eliminate all others

I am faced with a challenge where I need to eliminate array members that do not have a certain property. Take for example this scenario:

    const idToKeep = 1;

    const objList = [{
        id: 1,
        name: 'aaa',
      },
      {
        id: 4,
        name: 'bbb',
      },
      {
        id: 7,
        name: 'ccc',
      },
    ];

In this case, I want to remove all objects that do not have an id of 1. While I understand how to remove items from the list, my question is how to retain and remove only those that don't meet the criteria.

To achieve this, I can implement the following code snippet:

const filteredObjList = objList.filter(x => x.id === idToStay);

console.log(filteredObjList);

Answer №1

It's pretty much the same concept, just minus that enthusiastic punctuation mark

const idToRemain = 1;

const objectList = [{
        id: 1,
        name: 'aaa',
      },
      {
        id: 4,
        name: 'bbb',
      },
      {
        id: 7,
        name: 'ccc',
      },
    ];
    
    
const filteredObjects = objectList.filter(item => idToRemain === item.id);

console.log(filteredObjects);

Answer №2

It is my wish that this solution proves effective for you.

    let filteredResults = objList.filter((element) => {
        return element.id === 1;
    });
    console.log(filteredResults);

If the proposed solution resolves your issue, kindly mark it as the answer. Thank you!

Answer №3

let items = [
      {
        id: 1,
        name: 'apple',
      },
      {
        id: 2,
        name: 'banana',
      },
      {
        id: 3,
        name: 'cherry',
      },
    ];
    
var filteredItems = items.filter((item) => item.id === 3 );
console.log(filteredItems);

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

Component in Angular 2 for blocking UI

How can you effectively block the user interface of an Angular 2 component? Is this the correct method to use? <component [blockUI]="true"></component> ...

Why does Vue continuously insert undefined values when adding non-consecutive indexes to an array?

In my application, users can select values from a dropdown list and add them to an array by clicking the "add" button. The goal is to use the selected value's id as the index in the array. For example: List of Values 1 - Apple 3 - Bananas 8 - P ...

Creating a new row in a Tabulator component in React and retrieving the data

I have incorporated the react-tabulator library into my project and I am looking for guidance on how to dynamically add new rows once the tabulator has been rendered. Ideally, I would like to include a button below the tabulator that enables users to add a ...

Extracting data from a database using PEAR for Excel: Enumerating columns

One aspect of my website allows users to extract an Excel file using data from a database, with the help of the PEAR library. The Excel table that is generated currently has 32 columns. My main goal is to insert a 33rd column that assigns a number startin ...

Collaborate on Typescript Interfaces within a Firebase development environment

I've been developing a Firebase project using Angular for the frontend, and incorporating the @angular/fire library. Within this project, I have created multiple interfaces that utilize firebase and firestore types. For example: export interface ...

Confirming the information before submitting the form

My submit button is set up like this: <input class="create_button" name="commit" onclick="return validate_activity();" type="submit" value="Save"> I have noticed that this button always sends a request to the server regardless of wh ...

Proper sequencing of functions within a JavaScript file

I am currently reviewing the sequence of functions in my JavaScript file to ensure that I am calling the load and resize event handlers in the correct order. Check out a snippet from my code below: function init() { // code imgLoad.on('done', f ...

Tips for transferring a JavaScript object to a Node.js server

I must admit, I am positive that the solution to my issue is incredibly simple yet it has been evading me for more than a week now and causing me endless frustration. My current project involves creating a web app for quoting purposes within my workplace, ...

Is there a way to resolve the issue of my localStorage getting overridden on page refresh?

I am currently working on a simple React app and encountering an issue with the localStorage. Whenever I refresh the page, the todo list stored in the localStorage disappears. How can I ensure that the todos remain visible even after a refresh? Any sugges ...

TypeScript Redux expands the type system

Currently, I am working with Redux along with React and Typescript. I have been following the official Redux documentation's "Usage with TypeScript" section available at https://redux.js.org/usage/usage-with-typescript. export type AppDispatch = type ...

Looking to activate a button upon clicking a button on a different page using php and javascript

Is it possible for the first user logged in on one page to have a button, and when clicked, enable a disabled button on another page where the second user is logged in? This functionality needs to be implemented using PHP/JavaScript. Thank you in advance ...

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 ...

Tips for adding responses to input fields in AngularJS

I am looking to populate data into 3 inputs based on the JSON response I receive from my node server. However, despite receiving a response, I am unable to input it into the designated fields. Controller: $scope.edit = function(id, contact) { console.log ...

How to use jQuery to retrieve the style of an element based on a specific data attribute

I've been using bxSlider and I decided to create a unique custom pager using the pagerCustom option. My goal was to make the pager resemble a thumbnail pager, so I attempted to copy the style of each slide and attach it to the corresponding pager. For ...

Finding distinct values in a multidimensional array using JavaScript

When working with JavaScript, I created a multidimensional array using the following code: result.each(function(i, element){ init.push({ label : $(this).data('label'), value : $(this).val(), }); }); The resulting array in ...

The Function-supported Operation is having trouble implementing a modification related to Geohash/Geopoint - the Object Type requires a String format

Summary: My function-based Action that tries to set a GeoPoint as a Geohash property is failing with an error suggesting it was anticipating a string. I have an Object Type with a String property that has been designated as a Geohash in the property edito ...

Error: The function cannot be called because it is undefined

As a newcomer to JavaScript, I recently copied a script from jqueryui.com for the dialog widget and pasted it into my Yii project. However, upon testing the code, I encountered an error: Uncaught TypeError: undefined is not a function associated with the ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

What is the process for loading an image from the FileSystem using expo?

Can someone help with loading an image from FileSystem in expo? The fileUri is as follows: file:///Users/username/Library/Developer/CoreSimulator/Devices/B9799180-7428-41D8-A4BC-C3A34BF93043/data/Containers/Data/Application/3D502086-E077-42D5-9B56-A1DB788 ...

Issue: Angular CLI version 10.1.0 or newer is requiring a `tsconfig.base.json` file, which is not found

Currently working on my Angular 11 project, I am faced with the challenge of transitioning from tslint to eslint. When attempting the command below: ng add @angular-eslint/schematics An error arises: Error: Angular CLI v10.1.0 and later (and no tsconfig ...