[英]how to correctly map an obj and return a single value with several identical values ReactJS
I would like to explain my problem of the day.我想解释一下我今天遇到的问题。
currently i have an array of object目前我有一个对象数组
I map this table我映射这张表
[
{ id: "a", location: "FR", zone: "EU" } ,
{ id: "b", location: "FR", zone: "EU" } ,
{ id: "c", location: "ES", zone: "EU" } ,
{ id: "d", location: "ES", zone: "EU" } ,
]
to sort all the data I use a useEffect to retrieve only the values I need对所有数据进行排序,我使用 useEffect 仅检索我需要的值
useEffect(() => {
if (data) {
const location = data.map((e) => {
return {
label: e.location,
};
});
setLocations(locations);
}
}, [data]);
this works correctly.这工作正常。
except which returns me the following format除了返回我以下格式
0: {label: 'FR'}
1: {label: 'FR'}
2: {label: 'ES'}
4: {label: 'ES'}
and I would like to have the following format我想有以下格式
0: {label: 'FR'}
1: {label: 'ES'}
basically it removes the identical key基本上它删除了相同的密钥
iam open to any proposal thank you very much.我对任何建议持开放态度,非常感谢。
Since you're using location
as an id-like property that determines the uniqueness, you can do:由于您将
location
用作确定唯一性的类似 id 的属性,因此您可以执行以下操作:
const data = [ { id: "a", location: "FR", zone: "EU" } , { id: "b", location: "FR", zone: "EU" } , { id: "c", location: "ES", zone: "EU" } , { id: "d", location: "ES", zone: "EU" } , ]; console.log( Array .from(new Set(data.map(d => d.location))) .map(label => ({ label })) )
This first transforms the list to an array of strings.这首先将列表转换为字符串数组。 It uses a
Set
to get rid of duplicate strings.它使用
Set
去除重复的字符串。 Then, it transforms to the desired output format.然后,它转换为所需的输出格式。
data.map(d => d.location)
gives [ "FR", "FR", "ES", "ES" ]
data.map(d => d.location)
给出[ "FR", "FR", "ES", "ES" ]
Array.from(new Set(...))
gives [ "FR", "ES" ]
Array.from(new Set(...))
给出[ "FR", "ES" ]
(...).map(label => ({ label }))
gives the final output (...).map(label => ({ label }))
给出最终输出use filter and indexOf使用过滤器和 indexOf
data = data.filter(function (value, index, array) {
return array.indexOf(value) === index;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.