通过数组映射产生对象

Mapping through an array to produce an object

我有一个数组:

[
"2022-05-20",
"2022- 06-22",
"2022-06-20"
]

我想生成这样的对象:

{
    '2022-05-20': {disabled:true},
    '2022-06-22': {disabled: true},
'2022-06-20': {disabled: true},
  }

我尝试使用 for 循环,但它一直产生错误。 javascript 这可能吗?

这可能会完成工作。

const yourArray = ["2022-05-20", "2022-06-22", "2022-06-20"];
const obj = {};
for(const x of yourArray) obj[String(x)] = { disabled: true };
console.log(obj); // :)

创建变量 obj 来保存您想要的生成对象。迭代抛出你的数组并在当前迭代中使用字符串解析版本的值(解析以防万一,如果你已经知道数组是由字符串组成的,这是不必要的)将它保存为新对象的键,还为该键分配值 { disabled: true }.

这是一个单行解决方案:

let res = data.reduce((acc, curr) =>(acc[curr] = {disabled: true}, acc), {});

能做到:

let dates = [
  "2022-05-20",
  "2022- 06-22",
  "2022-06-20"
];

let newObj = Object.assign(...dates.map(key => ({[key]: {disabled: true}})));

console.log(newObj)

您也可以使用 Array#reduce as in the following demo. You can also use Array#map but you would have to use 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 );

正在使用 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 );