简体   繁体   中英

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

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, eg

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

You're somewhat on the right track, but what's data ? Why are you not doing anything with result ? And you should be looking at the Category property rather than ID.

This'll work:

function getCat(id) {
    let result = [];

    for (let item in Foods) {
        if (Foods.hasOwnProperty(item)) {
            Foods[item].forEach((food) => {
                if (food.Category == id) {
                    result.push(food);
                }
            });
        }
    }

    console.log(result);
}

First of all result array should be at global scope so that you can access it in another function, And in object you are having categories then each category has some data in array so after iterating over object, you need to iterate the items from array as well to get the value. Check the below code.

var result = [];
    function getCat(id){
     for(let item in Foods) {
        var foodItem = Foods[item];
        for(let i=0; i<foodItem.length; i++){
           if(foodItem[i].id == id) {
              result.push("<div class='box'><h2>" + foodItem[i].Name + "<br></div>"));
           } 
        }

      }
    }

function display() {
  alert(result);
}

display();

Iterator is wrong. You should do it like this:

function getCat(id){
    result = [];
    for(let item in Foods) {
        Foods[item].forEach(function(each){
            if(each.id == id) { // you cmpare to the wrong target
                // do something
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM