Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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(() => {
    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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Since you're using location as an id-like property that determines the uniqueness, you can do:

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. Then, it transforms to the desired output format.

  • data.map(d => d.location) gives [ "FR", "FR", "ES", "ES" ]
  • Array.from(new Set(...)) gives [ "FR", "ES" ]
  • (...).map(label => ({ label })) gives the final output
about 4 years ago · Juan Pablo Isaza Report

0

use filter and indexOf

data = data.filter(function (value, index, array) { 
  return array.indexOf(value) === index;
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!