JS - Destructuring by picking only what you need [duplicate] - javascript

This question already has answers here:
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
ES2015 deconstructing into an object [duplicate]
(1 answer)
How to get a subset of a javascript object's properties
(36 answers)
Closed 4 years ago.
I'm trying to understand ES6, specifically destructuring feature.
How can I translate these lines using destructuring?
const user = {...}
const sessionData = ({
session_id: user.session_id,
selector: user.selector,
validator: user.validator
})
I tried
const sessionData = {session_id, selector, validator} = user
But it raises a syntax error, because of course destructuring is for giving a certain variable a value from an object but I don't understand how to do something like this with an object

Use
const { session_id, selector, validator } = user;
Then
const sessionData = { session_id, selector, validator };

You could also do it like so (using anonymous functions)
const user = { session_id: 1, selector: "my-selector", validator: 1, unused: 3 };
const session = (({ session_id, selector, validator }) => ({ session_id, selector, validator }))(user);
console.log(session);

You can use a function to create the new object with the fields you want.
const original = { a: 1, b: 2, c: 3 };
const pick = (o, fields) => fields.reduce((acc, key) => {
acc[key] = o[key];
return acc;
}, {});
console.log(pick(original, ['a', 'b']));
Or use the comma operator to destructure and assign.
const original = { a: 1, b: 2, c: 3 };
const newone = ({ a, b } = original, { a, b });
console.log(newone);
But keep in mind that the comma operator creates global variables, if the variables to assign the destructure are not declared. Hope this helps.

Related

Get value from object in array: js [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
This is what my array looks like:
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
And I have the uuid key in the variable:
const uuid = '111-111-111';
Now based on this uuid, I would like to extract the value from the amountMoney: 44.04.
How do you write this in a nice way in js?
You can use Array.prototype.find:
items.find(item => item.uuid === uuid) // -> found object
Use Array.prototype.find to find the object if the property uuid of the object matches the value of the variable uuid. Before extracting the value for amountMoney check if the object was found.
Example,
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
const uuid = '111-111-111';
const foundItem = items.find(item => item.uuid === uuid);
if (foundItem) {
console.log(foundItem.amountMoney)
}

Mapping JavaScript Object Into An Array Of Hashes [duplicate]

This question already has an answer here:
'Unexpected token' syntax error in object returned by arrow function [duplicate]
(1 answer)
Closed 4 years ago.
I want to take a Javascript object and convert it into an array of hashes.
The following works to get just one element of the object and turn it into an array:
const coordinatesArray = items.map((item) => item.latitude)
Returns: [51.5165328979492, 51.5990409851074, 51.5990409851074, 51.5165328979492, 51.5098190307617, 51.5128326416016, 51.5098190307617, 51.501766204834, 51.514087677002, 51.4983825683594, 51.5294952392578, 51.5123977661133, 51.5011863708496, 51.5204887390137, 51.514087677002, 51.5117797851562, 51.5139465332031]
But when I try to create hash elements to make up the array, I get an error:
const coordinatesArray = items.map((item) => { x:item.latitude, y:item.longitude })
Returns: Uncaught Error: Module build failed: SyntaxError: Unexpected token, expected ;
What am I doing wrong?
Try the following:
const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))
Lambda functions returning objects need an extra bracket set () to distinguish them from a function body.
You need some parenthesis around the curly brackes, otherwise it is interpreted as block statement in arrow functions.
const coordinatesArray = items.map((item) => ({ x: item.latitude, y: item.longitude }));
Shorter with destructuring and short properties:
const coordinatesArray = items.map(({ latitude: x, longitude: y }) => ({ x, y }));
Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
In your case:
const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))
More Info here.

JS Recursive object assign [duplicate]

This question already has answers here:
How to deep merge instead of shallow merge?
(47 answers)
Closed 4 years ago.
I learned that when using Object.assign() it extends only the top level object. How can I deeply extend the object? For example, let's say I have the following source object:
const source = {
id: 1,
otherKey: {},
params: {
page: {
a: 1,
b: {}
},
data: {
b: 1
}
}
}
And I am using Object.assign() like this:
Object.assign({}, source, {
params: {
page: {
a: 2
}
}
}
The result will be:
{
id: 1,
otherKey: {},
params: {
page: {
a: 2
}
}
}
How can I preserve the params.data key and the params.page.b key in a shallow clone way.
oldObject.params.data === newObject.params.data // true
oldObject.params.page === newObject.params.page // false
oldObject.params.page.b === newObject.params.page.b // true
Note: This question is not the same as How to deep merge instead of shallow merge. The answers there does not give the expected results.
Check this bin that takes an answer from the above link.
So in your posted code, what happens is, if the source and target both contain the same key then nothing happens. The object is recursed down to the children. However if you simply change the inner block to this:
if (!target[key]) {
Object.assign(target, { [key]: {} });
}else{
target[key] = Object.assign({}, target[key])
}
mergeDeep(target[key], source[key]);
This will create a new assigned object for any key that is found in both the source and the target. Interestingly though, if you do this, your expected falseys will not show up in the console. This is because the target will always match the result, as it is the final mutated object. So in order to get your expected false results, you need to do something like the following:
var tester = source.params
const result = mergeDeep(source, b)
console.log(tester === result.params) // this will be false after the above addition
You can see your desired result here: http://jsbin.com/vicemiqiqu/1/edit?js,console

Destructuring assignment to costruct a new object - Is it possible? [duplicate]

This question already has answers here:
Is it possible to destructure an object and generate a new object in a single statement? [duplicate]
(2 answers)
How to get a subset of a javascript object's properties
(36 answers)
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
Is it possible to use destructuring assignment syntax to make it possible to extract data objects into another object instead distinct variables?
Example which produce distinct variables (foo, bar):
var {p: foo, q: bar} = {p: 42, q: true};
console.log(foo); // 42
console.log(bar); // true
I would need in stead to create a new object which contains the following properties as:
var n = {
foo: 42,
bar: true
}
It is not possible. The term destructuring implies that object is destructured to variables.
A way to not pollute the scope with temporary variables is to use IIFE for destructuring:
obj = (({ foo = 'foo', bar = 'bar' }) => ({ foo, bar }))(obj);
This will assign default values and will pick only valid keys from the object.
If picking is not necessary, the cleanest recipe to do this with native JS features is ES6 Object.assign:
obj = Object.assign({ foo: 'foo', bar: 'bar' }, obj);
Or ES2018 spread:
obj = { foo: 'foo', bar: 'bar', ...obj};
It sort of is, but you'll need two steps. You can't destructure directly from an object into another object, but you can make this elegant by using ES6 object notation and wrapping it into a function.
function transformObject(object) {
const { p: foo, q: bar } = object;
const newObject = {
foo,
bar
};
return newObject;
}
You cannot do it using destructuring, but you could use a helper function like this:
function retag(newStructure, source) {
var result = {};
for (var key in newStructure) {
result[key] = source[newStructure[key]];
}
return result;
}
console.log(retag(
{ foo: 'a', bar: 'b' },
{ a: false, b: 42, c: 'unused'}
));

Return object from arrow function [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 7 years ago.
I want to output object from arrow function (in a short form), so full code is:
somemethod(function(item) {
return {id: item.id};
})
with arrow functions it's:
somemethod((item) => {
return {id: item.id};
})
and now short form should be something like:
somemethod(item = > {id: item.id} )
that does not work, as well as this one:
somemethod(item = > {{id: item.id}} )
only one solution I found for now is to use create Object notation:
somemethod(item = > new Object({id: item.id}) )
is there another way?
For Objects you have wrap your object using parentheses or else it doesn't work
This is because the code inside braces ({}) is parsed as a sequence of statements
Try as below
var func = () => ({ foo: 1 });
refer : arrow functions
somemethod(item => ({ id: item.id }))
Test:
> a = item => ({id: item.id})
< function item => ({id: item.id})
> a({ id: 5, name: 7 });
< Object {id: 5}

Categories

Resources