2

I'm fairly new at creating anonymous functions and using map, what does ...i mean on the following lines of code. tia

const airlines = this.state.airlines.map(i => ( { ...i, editing : this.state.editing && i===item } ) )

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Rain Ramos
  • 41
  • 3
  • 3
    Its the spread operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – johnborges Jun 03 '19 at 02:43
  • i.e `{ ...{a: 1, b: 2}, c: 3 }` is `{ a: 1, b:2, c:3 }` and `[ ...[1, 2, 3], 4 ]` is `[1, 2, 3, 4]` – Julian W. Jun 03 '19 at 02:47
  • @user202729 yes there is, the assignment is made to the keys of the object that will be returned by `map`'s callback – Kaiido Jun 03 '19 at 02:49
  • @Kaiido After reading the linked question and answer again, it looks like that the *answer* includes the spread syntax for object, but not the question. Perhaps the question title should be changed. – user202729 Jun 03 '19 at 02:51
  • @user202729 we currently have no way to tell what is `i`. The linked question treats most common cases (Objects and Arrays), I doubt OP is using an exotic object which has its own Symbol.iterator. – Kaiido Jun 03 '19 at 02:59

1 Answers1

0

It's known as spread syntax, and in the current context it involves copying an object. It's the same as doing this:

const airlines = this.state.airlines.map(object => {
    object.editing = this.state.editing && object === item;
    return object;
});

So what we do is we create a shallow copy of the object, and we add properties to it. This is the purpose of spread syntax - to make a shallow copy, or to collect items for a shallow copy (known as rest syntax - collects the rest of the items). Here's a simplified example of spread syntax:

const arr = [{
  name: "Jack"
}, {
  name: "Joe"
}];    
const res = arr.map(e => ({ ...e,
  age: Infinity
}));    
console.log(res);
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79