Home > Enterprise >  Trying to return a filter() value from an array of objects based on conditionals
Trying to return a filter() value from an array of objects based on conditionals

Time:05-17

I'm trying to return only a part of my object as an array based on conditionals but I'm kinda stumped.

I have an array of objects and I want to return an array of names for each key : value they fit in.

I do get only the unique pairings but I'm returning the food key:value as well and all of it is still inside an object not a new array. Some insight would be greatly appreciated. Newer to coding.

const organizeNames = function (foods) {
 let foodNames = foods.filter((names) => {
  if (names.food === 'oranges') {
  return names.name;
 }
});

console.log(foodNames);
};
console.log(
  organizeNames([
   { name: 'Samuel', food: 'oranges' },
   { name: 'Victoria', food: 'pizza' },
   { name: 'Karim', food: 'pizza' },
   { name: 'Donald', food: 'pizza' },
  ])
 );

CodePudding user response:

You're really close here. What you need to incorporate is .map() to map your list of objects to a list of names. Your filter part works, partly by accident, so I've fixed it to be more correct (return names.food === 'oranges'), and then once you have your list of objects that match 'oranges' for their food, you map that filtered list into a list of names by doing .map(names => names.name)

const organizeNames = function (foods) {
  let foodNames = foods.filter((names) => {
    // only keep items whose .food property === 'oranges'
    return names.food === 'oranges'; // returns true or false
  }).map(names => {
    // map the filtered list of objects into a list of names by
    // returning just the object's .name property
    return names.name;
  });

  return foodNames;
};
console.log(
  organizeNames([
   { name: 'Samuel', food: 'oranges' },
   { name: 'Victoria', food: 'pizza' },
   { name: 'Karim', food: 'pizza' },
   { name: 'Donald', food: 'pizza' },
  ])
);

CodePudding user response:

The filter() callback function should just return true or false. Then you can use map() to get a specific property from each of the filtered items.

const organizeNames = function(foods) {
  let foodNames = foods.filter((names) => names.food == 'oranges').map(names => names.name);
  return foodNames;
}

console.log(
  organizeNames([{
      name: 'Samuel',
      food: 'oranges'
    },
    {
      name: 'Victoria',
      food: 'pizza'
    },
    {
      name: 'Karim',
      food: 'pizza'
    },
    {
      name: 'Donald',
      food: 'pizza'
    },
  ])
);

  • Related