我需要保留 { label: "Strawberry ?", value: "strawberry"}
,才能使用此代码
在提交到数据库时,我希望将所选值作为 strawberry: true, watermelon: true, pear: true,
const options = [
{ label: "Strawberry ?", value: "strawberry"},
{ label: "Watermelon ?", value: "watermelon" },
{ label: "Pear ?", value: "pear" },
]
我想把上面的数组转换成一个数组
const newArray = [
strawberry: true
watermelon: true
pear: true
]
我知道你会怎么做,也许这需要两步?
答案 0 :(得分:1)
如果您的意思是对象 {strawberry: true, watermelon: true, pear: true}
(关联数组),而不是数组,
const options = [
{ label: "Strawberry ?", value: "strawberry"},
{ label: "Watermelon ?", value: "watermelon" },
{ label: "Pear ?", value: "pear" },
];
const optionsObject = {};
options.forEach(({value}) => optionsObject[value] = true);
(如果你真的想这样做,你也可以用 .reduce
做到这一点:)
const optionsObject = options.reduce((obj, {value}) => {
obj[value] = true;
return obj;
}, {});