1

I come from a Python background so I am fairly new when it comes to iterating through JS objects. With Python you can create nested for loops to get into Key value pairs. My question is how do I iterate through this object and append the values greater than given number to an array.

The object I need to iterate through

const foodmenu = {
    title: 'Menu',
    sections: [
        {
            title: 'App',
            items: [
                {
                    title: 'Cookie',
                    available: true,
                    price: 3
                },
                {
                    title: 'Snicker',
                    available: true,
                    price: 12
                },
                {
                    title: 'Donuts',
                    available: true,
                    price: 11
                }
            ]
        },
        {
            title: 'FullMeal',
            items: [
                {
                    title: 'Steak',
                    available: false,
                    price: 33
                },
                {
                    title: 'Chinese Chicken',
                    available: true,
                    price: 14
                },
                {
                    title: 'Fried Chicken',
                    available: false,
                    price: 17
                }
            ]
        },

    ]
}

So to begin I need to create a function that takes in a number for price and take in the object. So this is what I tried so far, I don't know all of JS syntax but it's more pseudocode than working code at this point.

function findPriceAbove(price, foodmenu){
//create empty array to append the key names and values, E.G. ['App-Cookie(3)']    
const abovePriceArray = []

for (var key in foodmenu){
    if (foodmenu.hasOwnProperty(key)){
        for (const [key, value] of Object.entries(foodmenu)) {
                if foodmenu[value] > price and available == true;
                    abovePriceArray.push(key(App),name(Cookie),value(3)
              }
}
}
return abovePriceArray
}
2
  • can you show a sample output that you want with an example Commented Jan 18, 2021 at 1:57
  • so for instance if price is 13, abovePriceArray = ['FullMeal-Chinese Chicken(14)'] because "available is true" and it is the only price higher than 13 that is available. Output would be that array ['FullMeal-Chinese Chicken(14)'] Commented Jan 18, 2021 at 2:02

3 Answers 3

2

Here is an example using reduce(), iterating the items array of each category using forEach() and pushing a template literal of matching elements to at the accumulator.

const foodmenu = { title: 'Menu', sections: [{ title: 'App', items: [{ title: 'Cookie', available: true, price: 3 }, { title: 'Snicker', available: true, price: 12 }, { title: 'Donuts', available: true, price: 11 }] }, { title: 'FullMeal', items: [{ title: 'Steak', available: false, price: 33 }, { title: 'Chinese Chicken', available: true, price: 14 }, { title: 'Fried Chicken', available: false, price: 17 }] },] };

function findPriceAbove(price, foodmenu) {
  return foodmenu.reduce((a, category) => {
    category.items.forEach(item => {
      if (item.price > price && item.available) {
        a.push(`${category.title}-${item.title}(${item.price})`);
      }
    })
    return a;
  }, []); // <-- pass an empty array as the initial accumulator value
}

console.log(findPriceAbove(13, foodmenu.sections))

Sign up to request clarification or add additional context in comments.

2 Comments

Can you walk me through reduce at "a" are we declaring an empty array?
Yes, the second argument of the reduce(()={},[]) is the initial accumulator value which is passed as the first argument of the callback. In this case it is an empty array, but you can pass anything in, or if not passed the first element in the array will be used as the initial value.
1

You can do it like this

function getAbovePriceArray(givenPrice) {
    const abovePriceArray = [];

    foodMenu.sections.forEach((foodType) => {
        foodType.items.forEach((foodItem) => {
            if (foodItem.available && foodItem.price > givenPrice) {
                abovePriceArray.push(`${foodType.title}-${foodItem.title}(${foodItem.price})`);
            }
        })

    });

    return abovePriceArray;
}

Comments

1

I put the entire example... (just need to copy paste) I checked the code and it works as what I understood you are looking for:

const foodmenu = {
  title: 'Menu',
  sections: [
      {
          title: 'App',
          items: [
              {
                  title: 'Cookie',
                  available: true,
                  price: 3
              },
              {
                  title: 'Snicker',
                  available: true,
                  price: 12
              },
              {
                  title: 'Donuts',
                  available: true,
                  price: 11
              }
          ]
      },
      {
          title: 'FullMeal',
          items: [
              {
                  title: 'Steak',
                  available: false,
                  price: 33
              },
              {
                  title: 'Chinese Chicken',
                  available: true,
                  price: 14
              },
              {
                  title: 'Fried Chicken',
                  available: false,
                  price: 17
              }
          ]
      },

  ]
}

function findPriceAbove(minPrice, foodMenu){
  //create empty array to append the key names and values, E.G. ['App-Cookie(3)']    

  return foodMenu.sections.reduce((acum, current) => {
    return acum.concat(
      current.items
        .filter(item=> item.price > minPrice && item.available)
        .map(elem => `${current.title}-${elem.title}(${elem.price})`)
    )
  }, [])

  }

  console.log(
  findPriceAbove(10, foodmenu) //?
  ) 
/*
[
  'App-Snicker(12)',
  'App-Donuts(11)',
  'FullMeal-Steak(33)',
  'FullMeal-Chinese Chicken(14)',
  'FullMeal-Fried Chicken(17)'
]
*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.