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

170
Views
Dynamic object keys to array

I have an array of objects with dynamic country keys. I need to get the country key and put it into a new array. The array can contain more dynamic keys with the name of the countries.

const arr1 = [
  {
    id: 1,
    label: 'CA',
    value: 9,
    Canada: 9,
  },
  {
    id: 2,
    label: 'US',
    value: 7,
    'United States': 7,
  },
  {
    id: 3,
    label: 'AU',
    value: 5,
    Australia: 5,
  },
];
const result = ['Canada', United States', 'Australia']
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use a blacklist to dump all keys you don't want:

const arr1 = [
    { id: 1, label: 'CA', value: 9, Canada: 9 },
    { id: 2, label: 'US', value: 7, 'United States': 7 },
    { id: 3, label: 'AU', value: 5, Australia: 5 },
];

const blacklist = ['id', 'label', 'value'];

const countryNames = arr1.map(row => 
    Object.keys(row)
        .filter(key => !blacklist.includes(key))[0]);

console.log(countryNames)

Object.keys builds an array of keys for that row, then I filter those keys on the blacklist, and return the first remaining entry.

about 4 years ago · Juan Pablo Isaza Report

0

You can use flatMap to prevent getting an undefined value in the result when a key doesn't suit.

const data = [
    { id: 1, label: 'CA', value: 9, Canada: 9, },
    { id: 2, label: 'US', value: 7, 'United States': 7, },
    { id: 3, label: 'AU', value: 5, Australia: 5, },
    { id: 4, },
];

const blacklistedKeys = ['id', 'label', 'value'];

const result = data.flatMap(item => {
    const keys = Object.keys(item);
    const allowedKey = keys.find(key => !blacklistedKeys.includes(key));
    return allowedKey ? [allowedKey] : [];
});

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

A blacklist will break if you add more properties.

Have you considered filtering the ones whose first letter is uppercase?

const countryNames = arr1.map(row => 
    Object.keys(row)
        .filter(key => key[0] === key[0].toUpperCase())[0]);
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!