Kol*_*ale 3 javascript arrays mapping object
我有一个数组:
[
"2022-05-20",
"2022- 06-22",
"2022-06-20"
]
Run Code Online (Sandbox Code Playgroud)
我想生成一个像这样的对象:
{
'2022-05-20': {disabled:true},
'2022-06-22': {disabled: true},
'2022-06-20': {disabled: true},
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用 for 循环,但它不断产生错误。这可以用 JavaScript 实现吗?
Array#reduce
您可以像下面的演示一样使用。您也可以使用,但您也Array#map
必须使用。Object.fromEntries
const input = [ "2022-05-20", "2022- 06-22", "2022-06-20" ],
output = input.reduce(
(prev,cur) =>
({...prev,[cur]:{disabled:true}}), {}
);
console.log( output );
Run Code Online (Sandbox Code Playgroud)
使用Array#map
...
以下是您可以使用的方法Array#map
:
const input = [ "2022-05-20", "2022- 06-22", "2022-06-20" ],
output = Object.fromEntries(
input.map(date => [date, {disabled:true}])
);
console.log( output );
Run Code Online (Sandbox Code Playgroud)