Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to access object properties without referencing the object when provided as a function argument?

Tags:

javascript

Assume you got an object like var obj = {a:'foo',b:'bar'} you provide to a function function equal(x) { return x.a === x.b}; Is there a way to provide the object argument as scope to remove the object references within the function like so function equal(x) { return a === b};?

Side note: Syntax preferably works with ECMAScript 5th edition

Rationale: The idea behind the question is to cover cases where the object argument holds many properties {a:'foo',b:'bar',...,z:'baz'}, which would require repeating the object name quiet often.

like image 584
SomewhereDave Avatar asked Dec 08 '22 11:12

SomewhereDave


1 Answers

In ES6 we can use the destructuring assignment to get the mapping of the key-values in variables:

var obj = {a:'foo',b:'bar'};

//Using ES6 Destructuring syntax
function equal({a, b}) { return a === b};
console.log(equal(obj));

obj = {a:'bar',b:'bar'};
console.log(equal(obj));
like image 176
Fullstack Guy Avatar answered Jan 30 '23 11:01

Fullstack Guy