How to set value for all the items inside an array?
For example, I have the array: ["chin","eng","maths"]
I want to set it to {"chin" :true,"eng":true,"maths":true}
And push to firebase as a child.
One possible approach is to use Array.reduce() like this:
const input = ["chin", "eng", "maths"];
let obj = input.reduce((acc, item) => (acc[item] = true, acc), {});
console.log(obj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Or, you can go with spreading, but with a little overhead on performance:
let obj = input.reduce((acc, item) => ({...acc, [item]: true}), {});
reduceThe simplest way is to loop through the array using for...of and add each key to an object:
const keys = ["chin", "eng", "maths"],
output = {};
for (const key of keys) {
output[key] = true;
}
console.log(output)
Another option is to create a 2D array of key-value pair entries using map. Then use Object.fromEntries() to create the object
const keys = ["chin","eng","maths"]
const output = Object.fromEntries(keys.map(k => [k, true]))
console.log(output)
["chin","eng","maths"]to{"chin" :true,"eng":true,"maths":true}as a structure? Or as a string? The simple fact of changing[]to{}means a different structure. ([] = Array, {} = Object)