Home > Software engineering >  JavaScript Array's/methods and Functions
JavaScript Array's/methods and Functions

Time:01-01

export function getPlanetNames(data) {
  const pNames = data.planets;
  const results = pNames.filter(function (getNames) {
    return getNames.name;
  });
  return results;

'data' is in another file with an object array with attributes.

data = { planets: [{blah blah blah}] asteroids: [{blah blah blah blah}]}

why is my code above not pulling the planets array.name which is the attribute of the planets array.

CodePudding user response:

Actually filter function in Js doesn't returns specific key of object to assigned array. It is for filtering the elements of array based on conditions given. Try Map method.

    export function getPlanetNames(data) {
       const pNames = data.planets;
       const results = pNames.map(function (getNames) {
       return getNames.name;
     });
     return results;}

Now the results variable will have array of planet names.

CodePudding user response:

export function getPlanetNames(data) {
  const pNames = data.planets;
  const results = pNames.map(function (getNames) {
    return getNames.name;
  });
  return results;
}

This worked for me

  • Related