0

I am having a data like

var d = [{
  "AD": {
    "name": "Andorra",
    "native": "Andorra",
    "phone": "376",
    "continent": "EU",
    "capital": "Andorra la Vella",
    "currency": "EUR",
  }
}, {
  "AE": {
    "name": "United Arab Emirates",
    "native": "دولة الإمارات العربية المتحدة",
    "phone": "971",
    "continent": "AS",
    "capital": "Abu Dhabi",
    "currency": "AED",
  }
}, {
  "AF": {
    "name": "Afghanistan",
    "native": "افغانستان",
    "phone": "93",
    "continent": "AS",
    "capital": "Kabul",
    "currency": "AFN",
  }
}] 

and i want to get the name of each object using ES6 higher-order functions without using for or foreach.

i have tried filter and map but not knowing when to use what

Nikhil Savaliya
  • 2,138
  • 4
  • 24
  • 45

3 Answers3

0

You can easily achieve that using Array.prototype.reduce() as follows:

var d = [{
  "AD": {
    "name": "Andorra",
    "native": "Andorra",
    "phone": "376",
    "continent": "EU",
    "capital": "Andorra la Vella",
    "currency": "EUR",
  }
}, {
  "AE": {
    "name": "United Arab Emirates",
    "native": "دولة الإمارات العربية المتحدة",
    "phone": "971",
    "continent": "AS",
    "capital": "Abu Dhabi",
    "currency": "AED",
  }
}, {
  "AF": {
    "name": "Afghanistan",
    "native": "افغانستان",
    "phone": "93",
    "continent": "AS",
    "capital": "Kabul",
    "currency": "AFN",
  }
}] 

const names = d.reduce((acc, curr) => {
  const keys = Object.keys(curr);
  const name = curr[keys[0]].name;
  acc.push(name)
  return acc;
}, []);

console.log(names)
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
-1

The simply way to achieve that is for me :

var d = [{
  "AD": {
    "name": "Andorra",
    "native": "Andorra",
    "phone": "376",
    "continent": "EU",
    "capital": "Andorra la Vella",
    "currency": "EUR",
  }
}, {
  "AE": {
    "name": "United Arab Emirates",
    "native": "دولة الإمارات العربية المتحدة",
    "phone": "971",
    "continent": "AS",
    "capital": "Abu Dhabi",
    "currency": "AED",
  }
}, {
  "AF": {
    "name": "Afghanistan",
    "native": "افغانستان",
    "phone": "93",
    "continent": "AS",
    "capital": "Kabul",
    "currency": "AFN",
  }
}] 

d.map(item => {
 console.log(Object.keys(item));
})
KolaCaine
  • 2,037
  • 5
  • 19
  • 31
-1

If there are only one key per object (AD, AE, AF...) you can use something like :

const d = [{
  AD: {
    name: 'Andorra',
  }
}, {
  AE: {
    name: 'United Arab Emirates',
  }
}, {
  AF: {
    name: 'Afghanistan',
  },
}];

const reduced = d.map(x => x[Object.keys(x)[0]].name);

console.log(reduced);

If there can be multiple key like (AD, AE, ...) you can use something like :

const d = [{
  AD: {
    name: 'Andorra',
  },

  DF: {
    name: 'Paris',
  },
}, {
  AF: {
    name: 'Afghanistan',
  },
}];

const reduced = d.reduce((tmp, x) => [
  ...tmp,
  
  ...Object.values(x).map(y => y.name),
], []);

console.log(reduced);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69