Kola Ayanwale
Kola Ayanwale

Reputation: 185

Mapping through an array to produce an object

I have an array :

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

and I want to produce an object like this:

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

I tried using a for loop but it kept producing errors. Is this possible with javascript?

Upvotes: 8

Views: 16341

Answers (4)

PeterKA
PeterKA

Reputation: 24648

You can use Array#reduce as in the following demo. You can also use Array#map but you would have to use Object.fromEntries as well.

const input = [ "2022-05-20", "2022- 06-22", "2022-06-20" ],

      output = input.reduce(
          (prev,cur) => 
          ({...prev,[cur]:{disabled:true}}), {}
      );
      
      
console.log( output );

USING Array#map ...

Here is how you can use 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 );

Upvotes: 15

Bahador Raghibizadeh
Bahador Raghibizadeh

Reputation: 1265

Can do it:

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

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

console.log(newObj)

Upvotes: 5

aaronlukacs
aaronlukacs

Reputation: 489

Here is a one liner solution:

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

Upvotes: 4

Luka Cerrutti
Luka Cerrutti

Reputation: 707

This might get the job done.

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); // :)

Create the variable obj that is going to save the produced object you want. Iterating throw your array and using a string parsed version of the value in the current iteration (parsing just in case, if you already know the array is made of strings, this is kinda unnecessary) to save it as a key on the new object, also assigning to that key, the value { disabled: true }.

Upvotes: 3

Related Questions