I'm trying to destruct a map object with one single [key, value]
pair, as example:
var v = { foo: 'bar'};
function f({key, value}) {
console.log('key is ' + key);
console.log('value is ' + value);
}
f(v);
This example should print:
key is foo
value is bar
but it's actually printing:
key is undefined
value is undefined
How can I achieve this? Note: key names can vary.
You can't get the key and the value by destructuring, as far as I'm aware; there's no syntax to destructure an unknown key. You could do f({ foo }) to get the value 'bar' , but if key names vary destructuring won't work.
The delete operator is used to delete the key-value pair where the key is “key2”. console. log(obj); The output of the above code in the console will be: { key1: "value1", key3: "value3" }.
When only a single key is to be removed we can directly use the delete operator specifying the key in an object. Syntax: delete(object_name. key_name); /* or */ delete(object_name[key_name]);
Not sure you can destructor key / values directly inside the parameters.
But you could do it inside the function..
eg.
const v = { foo: 'bar'};
function f(o) {
const [key, value] = Object.entries(o)[0];
console.log('key is ' + key);
console.log('value is ' + value);
}
f(v);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With