[英]Assign a value to an object's property via map
i have an object with country codes and country names like this: 我有一个带有国家代码和国家名称的对象,如下所示:
countries = {'CA': {name: Canada}, 'GR': {name: Greece}, 'SG': {name: Singapore}}
Then i have another array like this: 然后我有另一个像这样的数组:
markets = ["CA", "GR", "SG"]
Then i want to create an array of objects for every instance of the markets array with with this shape: {label:..., value:....} So i'm writing 然后,我想为具有以下形状的市场阵列的每个实例创建一个对象阵列:{label:...,value:....}所以我在写
const martOptions = markets.map((i) => {
return {label: i, value: i}
})
But for the label i don't want to assign CA or GR. 但是对于标签,我不想分配CA或GR。 I want somehow to find the name of the country in the countries object and add it to the label so as to have something like this: {label: Canada, value: CA} and not {label: CA, value: CA}
. 我想以某种方式在国家对象中找到国家的名称并将其添加到标签中,以便具有以下内容: {label: Canada, value: CA} and not {label: CA, value: CA}
。 Any ideas? 有任何想法吗?
You just need to refer back to the countries
object to get the name associated with the current country code: 你只需要参考回到countries
反对获得与当前国家代码关联的名称:
const countries = {'CA': {name: 'Canada'}, 'GR': {name: 'Greece'}, 'SG': {name: 'Singapore'}} const markets = ["CA", "GR", "SG"] const martOptions = markets.map((i) => ({label: countries[i].name, value: i})) console.log(martOptions)
Note that countries[i].name
would give you an error if there was a code in the markets
array that didn't exist in the countries
object. 请注意,如果markets
数组中的代码不存在于countries
对象中,那么countries[i].name
会给您一个错误。
(Note also that if you put it in parentheses you can directly return the new object without needing the { return ... }
structure in the arrow function.) (还请注意,如果将其放在括号中,则可以直接返回新对象,而无需使用箭头函数中的{ return ... }
结构。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.