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

时间:2018-11-23 12:39:16

标签: javascript arrays object

如何自动从数组中将键分配给对象,以包含相同元素作为字符串?


我有一个空对象和一个数组:

const myObject= {};

const newsCategory = ['business', 'entertainment', 'general', 'health', 'science'];

我需要用键值对填充对象

应该是 newsCategory 数组中的每个元素。

应该是另一个对象的实例。

new GetNews({country: 'gb', category: newsCategory[element]});

我可以通过手动方式完成此任务,分别分配每个类别:

myObject.business = new GetNews({country: 'gb', category: newsCategory ['business']});

...与其余类别相同。

结果将是

{
    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"
                }
    
}


我需要自动执行此过程,例如以循环为例。

这是我的尝试,但不起作用。

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]"}
*/


如何自动从数组中将键分配给对象,以包含相同元素作为字符串?

1 个答案:

答案 0 :(得分:4)

您应该执行myObj.cat而不是myObj[cat],以便将cat评估为键值,否则将设置名为"cat"的键。

String.raw也很奇怪,请不要使用它。您的类别已经是字符串。

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