Utilizing object deconstruction in function parameters

const sampleObj = {
    apple: 1,
    orange: 2
};

let newFunction = (...objects) => {
   console.log(apple,orange); // ReferenceError: apple is not defined
};

newFunction(sampleObj);

I am looking to access the object properties directly within the function without using sampleObj.apple or sampleObj.orange.

Note: I am aware that I can manually define the arguments ({ apple, orange }), but I prefer not to do so as the object may have an unknown or variable number of properties.

Answer №1

Is this information helpful?

I assume you are looking to extract certain properties that you are familiar with while keeping the rest intact?

const obj = {
    foo: 1,
    bar: 2,
    unknown: 3,
    unknow: 4,
};

let fn = ({ foo, bar, ...other}) => {
    console.log(foo, bar); 
    console.log(other);
};

fn(obj);

Answer №2

When it comes to destructuring, objects and arrays have different behaviors:

const obj = {
    foo: 1,
    bar: 2
};

let fn = ({ foo, bar }) => {
    console.log(foo, bar); // ReferenceError: foo is not defined
};

fn(obj);


If you only need to iterate over properties, you can also use destructuring with values:

const obj = {
    foo: 1,
    bar: 2
};

let fn = (values) => {
    console.log(...values); // ReferenceError: foo is not defined
};

fn(Object.values(obj));

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

Passport appears to be experiencing amnesia when it comes to remembering the user

After extensive research online, I have yet to find a solution to my issue. Therefore, I am reaching out here for assistance. I am currently working on implementing sessions with Passport. The registration and login functionalities are functioning properl ...

Experiencing issues with implementing shopping cart logic using KnockoutJS. Need help

The Objective Create a dynamic list of products. The Scenario Overview In my online shopping application, I want to showcase the products I add to my shopping list in a sidebar when I click the 'add button' for each product. Brief Problem Sum ...

`Why am I having difficulty transmitting HTML content with Node.js through Mailgun?`

I've been facing issues with sending HTML in my emails. To troubleshoot and prevent errors, I've opted to utilize Mailgun's email templates. Although I can successfully send out the emails, the problem arises when I receive them - the HTML ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

How come the gridApi.on.edit.beginCellEdit function in angular-ui-grid does not immediately refresh the dropdown options after being updated?

I am encountering a similar issue as described in this post Regarding the assignment of ui grid value drop-down box before beginCellEdit event fires in Angular However, I have noticed a slight difference. Even after updating the editDropdownOptionArray, th ...

Encountering an unfamiliar property in JSX dynamic component

I am attempting to display components after dynamically determining their name, but I keep encountering this issue: Unknown property ent on the <resultComponent> tag. Please remove this property from the element. The problematic code is located w ...

What is the best way to swap out elements in my string with those from an array?

Struggling to replace special characters in file names before saving them to the Windows filesystem due to compatibility issues. For my initial approach, I used the replace() method repeatedly on the string to replace specific special characters. Here&apo ...

What's the best way to link two http requests in AngularJS?

Currently, I am facing the challenge of chaining two http calls together. The first call retrieves a set of records, and then I need to fetch finance data for each individual record. flightRecordService.query().$promise.then(function (flightRecords) { $ ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Utilizing Grunt-express and static routes: The server must include a method named 'listen' that functions in the same way as http.Server.listen

I've been working on setting up Grunt to launch my express server using grunt-express. Even after reviewing the documentation and a related Stack Overflow post, I'm still having trouble figuring it out. I've tested various configurations in ...

Load the values into the dropdown list based on the selection from the previous dropdown menu

Currently, I am working on implementing cloning functionality for select boxes. There are 3 select boxes: country, state, city. The user selects the country first which then populates the state select box based on the ID, and similarly, the city dropdown ...

The Daterangepicker feature is experiencing technical difficulties when implemented on Web Pages using ASP.NET MVC

I'm encountering issues with the daterangepicker script obtained from the adminlte.io template, which isn't working on MVC web pages. Even though it runs fine in PHP, it seems to fail once I switch to asp.net MVC. <html> <head> ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...

Discovering the Week by week commencement and conclusion dates utilizing angularjs

Previously, I was utilizing the angularjs-DatePicker from npm. With this plugin, I could easily select a date from the calendar. However, now I require two fields - FromDate and ToDate - to display the week StartDate and EndDate whenever a date within that ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

Create an HTTP-only cookie from the resolver function in Apollo GraphQL

My objective is to pass the 'res' from my context into a resolver in order to utilize 'context.res.cookie' within my signin function and send an http only cookie. Although my sign-in function works fine, I am unable to see the cookie ad ...

Laravel Mix causes errors when running `npm run dev` and breaks the package

My nodejs package is built using ES6 features such as 'let', the spread operator (...) and default values for function arguments. However, when I run npm run production with Laravel Mix, an error message appears: ERROR Failed to compile with ...

Can anyone explain why the Splice function is removing the element at index 1 instead of index 0 as I specified?

selectedItems= [5,47] if(this.selectedItems.length > 1) { this.selectedItems= this.selectedItems.splice(0,1); } I am attempting to remove the element at index 0 which is 5 but unexpectedly it deletes the element at index ...