Hexana Hexana - 1 year ago 67
Javascript Question

Javascript Push to Array if Condition is Met

I have the following Foods Object:

var Foods = {
"Fruits": [{
"id": "1",
"Name": "Granny Smith",
"Category": "1"
}, {
"id": "2",
"Name": "Raspberries",
"Category": "1"
}
],
"Potatoes": [{
"id": "3",
"Name": "Maris Piper",
"Category": "2"
}, {
"id": "4",
"Name": "Charlotte",
"Category": "2"
}]
}


What I would like to do is only push the produce that matches an id passed by a link.

<a href="javascript:void(0)" class="cat" id="2" onClick="getCat(this.id)">Get Foods</a>


This is what I have tried so far:

function getCat (id){
result = [];
for(let item in Foods) {
if(Foods[item].id == id) {
data[item].foreach(v=>result.push("<div class='box'><h2>" +
data[key].Name + "<br></div>"));
}
}
}

display();

function display() {
alert(result);
}


So if a user hits the link (which has an id of 2), the result array should contain "Charlotte" and "Maris Piper" but I am just drawing a blank.

Any help appreciated.

Cheers

Answer Source

Youre quite close, however theres a slight problem:

for(let item in Foods) {
  console.log(Foods[item]);
  /*
  [{
  "id": "1",
  "Name": "Granny Smith",
 "Category": "1"
   }, {
   "id": "2",
   "Name": "Raspberries",
   "Category": "1"
   }
]
*/

So youre iterating over the categories, which are arrays.

Foods[item].id

is undefined as its an array and not a product. So we need to iterate the array to, e.g.

var result=[];
Object.values(Foods).forEach(function(category){
 category.forEach(function(product){
   if(product.id===id){
     result.push(product);
   }
 });
});

Run

But if youre doing this quite often, it might be easier to create one product array once:

var products = Object.values(Foods).reduce((arr,cat)=>arr.concat(cat),[]);

So you can simply filter this whenever someone clicks a button:

var result = products.filter(product=>product.id === id);

Run

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download