guijob
guijob

Reputation: 4488

how to destruct a key pair object

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.

Upvotes: 13

Views: 16107

Answers (6)

mat.twg
mat.twg

Reputation: 745

let foo = {foo: 'bar'}
let [key, value] = Object.entries(foo).flat();

console.log(key);
console.log(value);

Upvotes: 4

fyasir
fyasir

Reputation: 2970

var v = { foo: 'bar'};

function f(obj) {
 var pair = Object.entries(obj)[0];
  console.log('key is ' + pair[0]);
  console.log('value is ' + pair[1]);
}

f(v);

Upvotes: 1

Rob Monhemius
Rob Monhemius

Reputation: 5144

This should work for objects with multiple properties too.

var object = { foo: 'bar', food: 'pizza'};

function f(object) {
  // get an array of all keys
  let keys = Object.keys(object); 
  
  // iteratate over this array 
  keys.forEach(key => {
    // output the current key and associated value
  	let property = object[key];
   	console.log('key is ' + key);
   	console.log('value is ' + property);
  });
}

f(object); 

Upvotes: 0

Keith
Keith

Reputation: 24221

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

Upvotes: 15

Nina Scholz
Nina Scholz

Reputation: 386728

You could use Object.entries for getting the entries of the object, which returns a key value array for each entry.

function f(object) {
    for (var [key, value] of Object.entries(object)) {
        console.log('key is ' + key);
        console.log('value is ' + value);
    }
}

f({ foo: 'bar' });

Upvotes: 6

Scott Marcus
Scott Marcus

Reputation: 65835

Not sure this is what you're looking for, but Object.keys() does do the trick.

var v = { foo: 'bar'};

function f(o) {
   console.log('key is ' + Object.keys(o)[0]);
   console.log('value is ' + o[Object.keys(o)[0]]);
}

f(v);

Upvotes: -1

Related Questions