Search code examples
javascriptobjectmapping

Javascript to return first and last name in a array of object getaccountfullname


const accounts = [
  {
    id: "5f446f2ecfaf0310387c9603",
    picture: "https://api.adorable.io/avatars/75/[email protected]",
    age: 25,
    name: {
      first: "Esther",
      last: "Tucker",
    },
    company: "ZILLACON",
    email: "[email protected]",
    registered: "Thursday, May 28, 2015 2:51 PM",
  },
  {
    id: "5f446f2ed46724f41c9fc431",
    picture: "https://api.adorable.io/avatars/75/[email protected]",
    age: 35,
    name: {
      first: "Ferrell",
      last: "Morris",
    },
    company: "ECOLIGHT",
    email: "[email protected]",
    registered: "Thursday, February 8, 2018 1:16 PM",
  }]

function getAccountFullNames(accounts) {

 
}

return accounts.name.first + account.name.last

What it to return Esther Tucker


Solution

  • Use Array::map() and object destructuring on an array item argument:

    function getAccountFullNames(accounts) {
      return accounts.map(({name:{first, last}}) => first + ' ' + last);
    }
    
    console.log(getAccountFullNames(accounts));
    <script>
    const accounts = [ { id: "5f446f2ecfaf0310387c9603", picture: "https://api.adorable.io/avatars/75/[email protected]", age: 25, name: { first: "Esther", last: "Tucker", }, company: "ZILLACON", email: "[email protected]", registered: "Thursday, May 28, 2015 2:51 PM", }, { id: "5f446f2ed46724f41c9fc431", picture: "https://api.adorable.io/avatars/75/[email protected]", age: 35, name: { first: "Ferrell", last: "Morris", }, company: "ECOLIGHT", email: "[email protected]", registered: "Thursday, February 8, 2018 1:16 PM", }]
    
    </script>