If condition inside the map function

Asked

Viewed 1,098 times

0

How can I put a condition if in my function for it not to return a value undefined?

This is my job:

keys.map(key => ({ key, value: data[key] }))

She returns this:

[ { key: 'a', value: 2 },
  { key: 'b', value: 2 },
  { key: 'c', value: 2 },
  { key: 'd', value: undefined },
  { key: 'e', value: undefined },
  { key: 'f', value: 2 } ]

I tried in some ways but without success.

One of my attempts:

keys.map(key => (if(data[key]!=undefined) {{key, value: data[key]}}))
  • 1

    If you just want to eliminate the values undefined you don’t need a map, but of a filter. The map sets a 1:1 relation and always returns an output for each input.

  • To address issues related to Arrays and Objects I strongly recommend you to use https://underscorejs.org - a Javascript library that provides a range of auxiliary programming functions . For example, in this case just do this: _.without(keys, undefined) and returns a copy of the array without the Undefined

1 answer

2


You cannot remove items directly by map, since, by definition, this method returns an array of the same length as the initial array, making only modifications to its values.

In that case, you would have to use the filter after the map to remove unwanted elements from the list. Something like this:

const data = {
  a: 2,
  b: 2,
  c: 2,
  d: undefined,
  e: undefined,
  f: 2
}

const keys = ['a', 'b', 'c', 'd', 'e', 'f']

const final = keys
  // Esse `map` faz exatamente a mesma coisa que a sua pergunta:
  .map((key) => ({ key, value: data[key] }))
  // Esse `filter` irá manter no array somente valores que
  // sejam diferentes (`!==`) de `undefined`.
  .filter((obj) => obj.value !== undefined)

console.log(final)

Note in the code snippet above that the objects whose property value was equal to undefined were removed from the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.