Is it possible for object destructuring in Javascript to include dynamic non-rest keys using ...rest?

Suppose we have an object:

const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };

My goal is to filter out specific keys from this object to create a smaller one. I am aware of the following syntax for achieving this:

const { key1, key2, ...rest } = obj;

The rest variable will then contain

{ key3: "value3", key4: "value4" }
.

Is it possible to achieve a similar outcome dynamically, without having to hard-code key1 and key2? Let's assume these unwanted keys are stored in an array called unwantedKeys, whose value (

["key1", "key2"]
) and length can only be determined during runtime.

Answer №1

Is it possible to achieve this dynamically without hard-coding key1 and key2? Let's assume they are stored in an array called unwantedKeys, which is determined only at runtime.

Yes, but not completely dynamic. You would need to know the number of keys in advance. For example, for two keys:

const { [unwantedKeys[0]]: unused1, [unwantedKeys[1]]: unused2, ...rest } = obj;

const unwantedKeys = ["key1", "key2"];
const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };
const { [unwantedKeys[0]]: unused1, [unwantedKeys[1]]: unused2, ...rest } = obj;
console.log(rest);

This approach might not be suitable for your scenario since the length of unwantedKeys is only known at runtime. :-) (Edit: It has been confirmed that the length is indeed only known at runtime.)

Since you require a dynamic solution, syntax alone won't suffice; however, you can utilize standard library tools like Object.entries, Array.prototype.filter, and Object.fromEntries:

const rest = Object.fromEntries(
    Object.entries(obj).filter(([key]) => !unwanted.includes(key))
);

const unwantedKeys = ["key1", "key2"];
const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };
const rest = Object.fromEntries(
    Object.entries(obj).filter(([key]) => !unwantedKeys.includes(key))
);
console.log(rest);

Alternatively, with the use of a Set, particularly if the list of unwantedKeys is extremely long and efficiency is a concern (unlikely :-)):

const unwantedSet = new Set(unwantedKeys);
const rest = Object.fromEntries(
    Object.entries(obj).filter(([key]) => !unwantedSet.has(key))
);

const unwantedKeys = ["key1", "key2"];
const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" };
const unwantedSet = new Set(unwantedKeys);
const rest = Object.fromEntries(
    Object.entries(obj).filter(([key]) => !unwantedSet.has(key))
);
console.log(rest);

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

generate new array using auxiliary array

I am currently using PHP to import fixed width text files into a database. Although my code is functional, I am looking to enhance its efficiency to handle multiple fixed width text files with different structures. Here is my current code snippet: $file ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

Eliminating blank objects from an array in Angular 8

Looking to remove empty objects from an array in Angular8 and get its length Array: [ {data01: "abc", data02: "cde", data03: "fgh", data04: "", data05: ""}, {data01: "abc", data02: "cde", data03: "", data04: "", data05: ""}, {data01: "abc", data02: "cde", ...

What benefits and drawbacks come with setting up JS libraries in resource files compared to package.json?

Configurations for JavaScript libraries such as Babel, Nyc, Eslint, and many others can be specified in resource files or within the package.json. For example, Babel can be set up in a .babelrc file or through a babel entry in the package.json. What are ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Unable to get ajax Post to function properly

Looking to save an object on a restful server, I attempted using an HTML form which worked fine. However, when trying it with JavaScript, I encountered some issues. Here's the code snippet: var app2={"user_id" : seleVal, "name":nome2, "img":img2, "ty ...

Running Bootstrap-select alongside Bootstrap 5 without encountering any errors

Currently working on a project with Bootstrap 5 (template-based) and encountered an issue while trying to add bootstrap-select (version 1.13.14) to the mix. The console is throwing these errors: Uncaught TypeError: Cannot read properties of undefined (rea ...

Errors in TypeScript Compiler for using react-bootstrap in SPFx project

After setting up an SPFX Project with Yeoman generator and including react-bootstrap as a dependency, I encountered errors when using react-bootstrap components and running gulp serve. The error messages are as follows; does anyone have any solutions to ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

Tips on adjusting the hover color in the data grid

I want to adjust the color of the Datagrid when hovering over it, does anyone know how to do this? The default color displayed is light blue, but I would like to change it to a different color. Can someone please assist me with this? Looking for document ...

Save a CSV file into a list, locate a specific key within the list, and retrieve the fourth value associated with that key

After thorough revision, the question now reads as follows: Take a look at this content in database.csv: barcode,ScQty, Name , Qty ,Code 123456 , 3 ,Rothmans Blue , 40 ,RB44 234567 , 2 ,Rothmans Red , 40 ,RB30 345678 , 2 ,Rothmans Gre ...

"Learn how to dynamically bind static data from an AJAX call using jQuery in a seamless

Hey there! I'm fairly new to jquery and I have a graph that currently receives data statically. However, I'd like to make it dynamic instead. Here's the current static data: var data = [ { label: "New Request", data: 1.7, color: "# ...

The error message "Uncaught ReferenceError: exports is not defined and require" indicates that

I am currently developing an app using angularjs and typescript, but I've encountered a persistent error that has me stumped. Below is the snippet of my code: export var NgApp = new application.Startup(); ///<reference path="../../../../../typin ...

Exploring the relationship between $resource and controllers

I am currently working on deciphering the code snippets below. From what I gather, there are three resource objects - CategorySrv, ArticleSrv, and SearchSrv that interact with REST server data sources. app.factory('CategoryService', function($re ...

Updating a select menu with AJAX without the need for a <div> tag within the form

Utilizing an ajax call to dynamically update a select menu is a common practice. The ajax call fetches the options from a separate .php file and populates the select menu accordingly. Below is the code snippet for inserting the dynamic content using JavaS ...

Tips for retrieving the posted object in angularJS

My current challenge involves creating an object with a defined name, posting it into a database, and then immediately finding its position and obtaining its id. However, I have noticed that using "get" right after "post" retrieves the data before it' ...

Expandable Grid with UI-GRID - Automatically expand a row when clicked on

I prefer not to utilize the default + icon for expanding the row. The row should expand when clicked anywhere on it. I attempted the following: HTML <div ui-grid="gridOptions" ui-grid-expandable class="grid"> Controller var app = angular.module( ...

Is it possible to declare language features in Typescript? For example, changing `!variable` to `no variable`

Can Typescript language features be declared within the app's source code? I want to enhance code clarity by implementing a small feature. Modified Null Test if (no userDetails) { // handle null } This new null test syntax is a little more conc ...

Using a JavaScript variable in a script source is a common practice to dynamically reference

I have a scenario where an ajax call is made to retrieve json data, and I need to extract a value from the json to add into a script src tag. $.ajax({ url: "some url", success: function(data,response){ console.log("inside sucess"); ...