[英]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.