简体   繁体   English

将键值对从数组添加到对象-Javascript

[英]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. 关键字应该是newsCategory数组中的每个元素。

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" . 代替myObj.cat您应该执行myObj[cat]以便将cat评估为键值,否则将设置名为"cat"的键。

Also String.raw is weird, don't use that. 另外String.raw也很奇怪,请不要使用它。 Your categories are strings already. 您的类别已经是字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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