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?
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 );
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With