1

I have the following array of objects coming from my database:

dataFromDB = [
  { src: 'stringWithSource1',
    selected: true
  },
  { src: 'stringWithSource2',
    selected: false
  },
  { src: 'stringWithSource3',
    selected: true
  },
  AND SO ON...
];

When I fetch it from the database I need to store on client-side in a state that must be an array of strings, containing only the src property of the objects that are selected: true.

Example:

myState = [
  'stringWithSource1',
  'stringWithSource3',
  AND SO ON...
]

QUESTION

The line where I'm assigning this, is like the following (see code below):

I tried but that doesn't work because I'm keeping the unselected src as null instead of just skipping them.

setProductDetails({
  // ... other properties,
  images: dataFromDB.images.map((item) => {
    return item.selected ? item.src : null;
  }
});

How can I achieve this behavior in a single line like this? I know I could create an auxiliar variable and handle this. But I would like a one-liner in this case. Is this possible? It feels like I should filter and map at the same time?

2
  • " in a single line" - Why? Make it as detailed as necessary that you or whoever is reading the code immediately understand what is happening here. Commented May 30, 2019 at 18:18
  • Because I'm doing this inside a setState(). Thanks! Commented May 30, 2019 at 18:20

1 Answer 1

5

You need two parts, because the filtering does not map a value, but the original items.

You could filter by selected and then map src.

images: dataFromDB.images
    .filter(({ selected }) => selected)
    .map(({ src }) => src)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.