0

I need to keep { label: "Strawberry 🍓", value: "strawberry"}, for this code to work with the in react though when submitting to the database i would like to have the selected values sent through as strawberry: true, watermelon: true, pear: true,

const options = [
    { label: "Strawberry 🍓", value: "strawberry"},
    { label: "Watermelon 🍉", value: "watermelon" },
    { label: "Pear 🍐", value: "pear" },
]

I would like to convert the above array to an array of

const newArray = [
strawberry: true
watermelon: true
pear: true
]

I would have a clue how you would do it maybe it's a two step thing?

1 Answer 1

1

If you really mean an object {strawberry: true, watermelon: true, pear: true} (an associative array), not an Array,

const options = [
    { label: "Strawberry 🍓", value: "strawberry"},
    { label: "Watermelon 🍉", value: "watermelon" },
    { label: "Pear 🍐", value: "pear" },
];
const optionsObject = {};
options.forEach(({value}) => optionsObject[value] = true);

(You can also do this with .reduce if you really want to:)

const optionsObject = options.reduce((obj, {value}) => {
  obj[value] = true;
  return obj;
}, {});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, you most have been coding for 20 years to know this lol

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.