简体   繁体   中英

add key value pairs to object from an array - Javascript

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?

Instead of myObj.cat you should do myObj[cat] so that cat is evaluated as the key value, otherwise you're setting a key named "cat" .

Also String.raw is weird, don't use that. Your categories are strings already.

newsCategory.forEach((category) => {
        myObj[category] = new GetNews({country: 'gb', category: category});
    })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM