Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map array of strings as object properties

I have an array like so.

const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"]

And I have the following initial state

state = {
options:{}
}

If I want to map this array to my state and assign each indexes string as a property of this.state.options how would I go about doing that?

So end result would be like:

console.log(this.state.options)

output: {king: null, henry:null, died:null, while:null, drinking:null, chocolate: null, milk:null}

I think it would be undefined after that instead of null... But any suggestions?

like image 795
Snoopy Avatar asked Nov 29 '22 21:11

Snoopy


2 Answers

I believe you are rather looking for reduce and not map

const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"];

const state = {
  options: array.reduce( (current, item) => {
      current[item] = null;
      return current;
    }, {})
};

console.log( state );
like image 197
Icepickle Avatar answered Dec 05 '22 03:12

Icepickle


You can use the Object.fromEntries function:

const array = ["king", "henry", "died", "while", "drinking", "chocolate", "milk"];
state = {
    options: Object.fromEntries(array.map(value => [ value, null ]))
};

Your user agent may not provide Object.fromEntries with its scripting host -- the function is part of ECMAScript 2019 aka the 10th edition -- but you can use a stand-in until it does:

if(!Object.fromEntries)
    Object.fromEntries = entries => entries.reduce((result, entry) => (result[entry[0]] = entry[1], result), {});

I prefer to use parts of language or API that I expect to become available broadly later, by providing a stand-in implementation until such time these become available, at which time the code will, without any modifications, use the native implementation automatically (the above is evidently a conditional stand-in a or polyfill as it is also called).

like image 29
amn Avatar answered Dec 05 '22 05:12

amn