1

I was following the answer in this question to filter a key-value pair in JS.

I have an Object of key-value pairs. I am trying to do something like this

{
   Object.entries(this.state.passengers)
      .filter(([key, passenger]) => passenger.flightNumber === this.props.flightNumber)
      .map(([key, passenger]) => {
         return ( 
            <tr key = {key}>
            //...JSX code
         )
      })
}

I get the warnings in console that key is not used. I am not finding the right syntax to avoid passing key as an argument to filter method. I want to pass the key to subsequent map method though. Please help. I am new to JS.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Mohammed Shirhaan
  • 555
  • 1
  • 11
  • 27
  • 2
    You can use `Object.values` if you just want the values, then grab the value in your callback like so: `passenger =>` – Nick Parsons Mar 18 '20 at 12:45
  • @NickParsons, I edited my question. What should I do if I want to pass it to map method? – Mohammed Shirhaan Mar 18 '20 at 12:48
  • I see now, you can try replace `key` with `_` in your filter method - `_` is commonly used to denote unused arguments, so your console may not complain about it - otherwise, you could get the `Object.keys()` from your object, and get the value using the key `this.state.passengers[key]` if you're really worried about solving the warning – Nick Parsons Mar 18 '20 at 12:49
  • ```.filter``` does not require key, but ```.map``` does, and you are already passing the key correctly to the element. So just remove ```key``` from ```.filter``` – Altair312 Mar 18 '20 at 12:49
  • @NickParsons same warning : warning '_' is defined but never used – Mohammed Shirhaan Mar 18 '20 at 12:51
  • 1
    @MohammedShirhaan one other idea may be to not to define a variable for the first array slot, so `([, passenger]) =>` might remove the warning? – Nick Parsons Mar 18 '20 at 12:55
  • 1
    @NickParsons, I tried the same. It is working. Thanks buddy. – Mohammed Shirhaan Mar 18 '20 at 12:56

1 Answers1

1

You have a few options here, the easiest would most likely be to ignore the first array value in your destructuring assignment so that key is never defined in your .map() callback in the first place:

.map(([, passenger]) => {

Additionally, another approach may be to use Object.keys(), and then get the value via the key:

Object.keys(this.state.passengers)
  .filter(key => this.state.passengers[key].flightNumber === this.props.flightNumber)
  .map(key => {
    return ( 
      <tr key = {key}>
      //...JSX code
    )
  })
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64