[英]add key value pairs to object from an array - Javascript
如何自動將鍵從數組分配給對象以及將值包含為與字符串相同的元素的過程?
我有一個空對象和一個數組:
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]"} */
如何自動將鍵從數組分配給對象以及將值包含為與字符串相同的元素的過程?
代替myObj.cat
您應該執行myObj[cat]
以便將cat
評估為鍵值,否則將設置名為"cat"
的鍵。
另外String.raw
也很奇怪,請不要使用它。 您的類別已經是字符串。
newsCategory.forEach((category) => {
myObj[category] = new GetNews({country: 'gb', category: category});
})
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.