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']
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.
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);
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]);