0

I was looking at someone else's code on Stack Overflow (this answer) and saw something weird. Something I've never seen before. Also, I could not find any documentation.

This code (based on the code in the answer) is an example:

let data = [
  { records: "productId*amount*tax1*tax2*tax3", id: 467 },
  { records: "111*2000*10*12*13", id: 278 },
  { records: "113*3000*10**", id: 787 }
];

let ids = data.map(({ id }) => console.log(id));

So apparently, when you use ({id}) as an argument for the callback, the argument does not contain the item in the array, but the value of that property of the item (object) in the array.

Anybody know what's going on here?

Sander_P
  • 1,787
  • 1
  • 13
  • 37

4 Answers4

1

Yea its called destructuring

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

He destructure the property id out of the argument object

bill.gates
  • 14,145
  • 3
  • 19
  • 47
0

This would work with any object not just in a map array method. Lets say you have an object data.

const data= {name: "price", value: 111};

You can access the value in there 2 ways.

const value = data.value

is the same as

const {value} = data
0

Yes, with ES6 and above, features for destructuring were introduced. In this instance, the argument passed into the map function is the property id of an object in the data array. Please see scenario below:

// create an object with id and label
const originalObj = { id: 1, label: 'First Item' };
/* create values from keys in object done via destructuring.  
   Here we get the values of the keys in the object by enclosing the 
   keys in the declaration 
   and set it equal the object
   with the properties. This will create 
   variables id and label and set them to 
   values 1 and 'First Item'.  This is what is happening in the map 
   call 
*/
const { id, label } = originalObj;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Paul
  • 460
  • 2
  • 7
0

I already knew about destructuring (though clearly not completely). Since the other answers are either not about function parameters, or just give a link, I'll answer it myself.

On developer.mozilla.org it is called Unpacking fields from objects passed as function parameter. With a very clear example:

const user = {
  id: 42,
  displayName: 'jdoe',
  fullName: {
    firstName: 'John',
    lastName: 'Doe'
  }
};

function userId({id}) {
  return id;
}

function whois({displayName, fullName: {firstName: name}}) {
  return `${displayName} is ${name}`;
}

console.log(userId(user)); // 42
console.log(whois(user));  // "jdoe is John"
Sander_P
  • 1,787
  • 1
  • 13
  • 37