[英]Javascript Push to Array if Condition is Met
我有以下食品對象:
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"
}]
}
我只想推送與鏈接傳遞的ID相匹配的農產品。
<a href="javascript:void(0)" class="cat" id="2" onClick="getCat(this.id)">Get Foods</a>
到目前為止,這是我嘗試過的:
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);
}
因此,如果用戶點擊鏈接(其ID為2),則結果數組應包含“ Charlotte”和“ Maris Piper”,但我只是在畫一個空白。
任何幫助表示贊賞。
干杯
您距離很近,但是有一個小問題:
for(let item in Foods) {
console.log(Foods[item]);
/*
[{
"id": "1",
"Name": "Granny Smith",
"Category": "1"
}, {
"id": "2",
"Name": "Raspberries",
"Category": "1"
}
]
*/
因此,您可以遍歷數組的類別。
Foods[item].id
未定義為其數組而不是產品。 因此,我們需要迭代數組,例如
var result=[];
Object.values(Foods).forEach(function(category){
category.forEach(function(product){
if(product.id===id){
result.push(product);
}
});
});
但是,如果您經常這樣做,一次創建一個產品數組可能會更容易:
var products = Object.values(Foods).reduce((arr,cat)=>arr.concat(cat),[]);
因此,只要有人單擊按鈕,您就可以對此進行過濾:
var result = products.filter(product=>product.id === id);
您在正確的道路上走了,但是什么是data
? 為什么不對result
做任何事情? 並且您應該查看Category
屬性而不是ID。
這將起作用:
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);
}
首先, result array
應該位於全局范圍內,以便您可以在另一個函數中訪問它;在對象中,您具有類別,然后每個類別在數組中都有一些數據,因此在對象上進行迭代之后,您需要對數組中的項目進行迭代,如下所示:很好地獲得價值。 檢查以下代碼。
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();
迭代器是錯誤的。 您應該這樣做:
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
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.