Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to destruct a key pair object

Tags:

javascript

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.

like image 502
guijob Avatar asked Mar 02 '18 16:03

guijob


People also ask

How do you Destructure key-value pairs?

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.

How do you remove a particular key-value pair from an array of objects?

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" }.

How do you remove a key-value pair from an object in typescript?

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]);


1 Answers

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); 
like image 63
Keith Avatar answered Sep 20 '22 06:09

Keith