最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Push to Array if Condition is Met - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Jul 27, 2017 at 9:17 Supradeep 3,2661 gold badge17 silver badges28 bronze badges asked Jul 27, 2017 at 9:03 HexanaHexana 1,1352 gold badges13 silver badges35 bronze badges 4
  • what is your variable result = []; scope? is it a global scope? – Ataur Rahman Munna Commented Jul 27, 2017 at 9:10
  • Whats data ???? And js is typesafe, so its onclick and forEach – Jonas Wilms Commented Jul 27, 2017 at 9:10
  • Sorry should be a Foods object. – Hexana Commented Jul 27, 2017 at 9:13
  • I think you might be looking for array.filter, but it is pletely unclear what your data looks like and what you want to get out of it. – Rob Commented Jul 27, 2017 at 9:13
Add a ment  | 

4 Answers 4

Reset to default 5

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

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
            }
        });
    }
}
发布评论

评论列表(0)

  1. 暂无评论