0

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?

1 Answer 1

4

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});
    })
};
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for pointing out my mistake, your solution worked well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.