How can I automate the process of assigning the key to an object from an array and the value to contain the same element as a string?
I have an empty object and an array:
const myObject= {};
const newsCategory = ['business', 'entertainment', 'general', 'health', 'science'];
I need to populate the object with key-value pairs.
The key should be each element from the newsCategory array.
The value should be an instance of another object.
new GetNews({country: 'gb', category: newsCategory[element]});
I can do this the manual way, assigning each category individually:
myObject.business = new GetNews({country: 'gb', category: newsCategory ['business']});
...and the same to the rest of the categories.
The result would be
{
business: GetNews {
category: "business"
country: "gb"
}
entertainment: GetNews {
category: "entertainment"
country: "gb"
}
general: GetNews {
category: "general"
country: "gb"
}
health: GetNews {
category: "health"
country: "gb"
}
science: GetNews {
category: "science"
country: "gb"
}
}
I need to do this process automatically, with a loop for example.
This is my attempt but it's not working.
newsCategory.forEach((category) => {
let cat = String.raw`${category}`; //to get the raw string
myObj.cat = new GetNews({country: 'gb', category: category});
})
};
/*
output:
{cat: "undefined[object Object][object Object][object Obj…ect][object Object][object Object][object Object]"}
*/
How can I automate the process of assigning the key to an object from an array and the value to contain the same element as a string?