1

const colors = [{id: 1, color: "yellow", picked: true}, {id: 2, color: "green", picked: false}, {id: 3, color: "red", picked: false}];

const pickedColor = colors.find(color => color.picked)
console.log(pickedColor)

This snippet returns an object where picked color is located, in this case it's "yellow". However I need to get this value to be stored in const pickedColor instead of having an entire object there. I know I can create another varibale and access it with dot notation, like const finalColor = pickedColor.color; but is there a way to return just "yellow" directly into const pickedColor?.

Dev
  • 355
  • 1
  • 7
  • 24
  • 4
    You can access it directly after find: `colors.find(...).color`, or use [optional chaining](https://stackoverflow.com/a/62359000/5648954) if the object might not be found: `colors.find(...)?.color` – Nick Parsons Dec 21 '20 at 00:28

1 Answers1

0

Just access the property of the object that you wish to retrieve. Also, naming your variables more specifically can help to understand what your code does.

const colorObjects = [{id: 1, color: "yellow", picked: true}, {id: 2, color: "green", picked: false}, {id: 3, color: "red", picked: false}];

const pickedColorObject = colorObjects.find(color => color.picked)
console.log(pickedColorObject.color)
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71