gpt4 book ai didi

javascript - 在 Angular JS Controller 中遍历复杂的 JSON 数组并显示特定值

转载 作者:行者123 更新时间:2023-11-30 15:22:25 26 4
gpt4 key购买 nike

{
"products":[
{
"recommendation":{
"currentLevel":79,
"maxLevel":100
},
"items":[
{
"id":"10600",
"title":"Hampton Cookset - 8 Piece",
"category":"STAINLESS STEEL",
"imageUrl": "http://localhost/img/001.jpg",
"unitsInCartons": 10,
"unitCost":4.52,
"packSize":10,
"secondaryCategory":"Chairs"
}
]
},
{
"recommendation":{
"currentLevel":79,
"maxLevel":100
},
"items":[
{
"id":"10870",
"title":"MELAMINE BOWL",
"category":"BOWLS",
"imageUrl":"http://localhost/img/001.jpg",
"unitsInCartons":6,
"unitCost":0.93,
"packSize":5,
"secondaryCategory":"Kids Home"
},
{
"id":"10820",
"title":"PP YUM YUM CUP",
"category":"CUPS/MUGS",
"imageUrl":"http://localhost/img/002.jpg",
"unitsInCartons":12,
"unitCost":0.7,
"packSize":25,
"secondaryCategory":"Kids Home"
}
]
}
]
}

我正在尝试遍历上述 JSON 代码,我的目标是显示所有 titlecategoryunitsInCartonunitCostpackSize 值在 Angular JS 中以表格的形式显示在 View 中。

我是 Angular 的新手,希望获得一些关于如何准确迭代以完成我的任务的指导。

最佳答案

您可以使用 Angular 嵌套 ng-repeat 来完成它,但这对性能不利。我建议首先解析数据以获得预期的格式,然后只使用一个 ng-repeat

对产品和项目使用 .map 函数,我能够输出预期的结果(通过在最后展平结果)。

var data = {
"products":[
{
"recommendation":{
"currentLevel":79,
"maxLevel":100
},
"items":[
{
"id":"10600",
"title":"Hampton Cookset - 8 Piece",
"category":"STAINLESS STEEL",
"imageUrl": "http://localhost/img/001.jpg",
"unitsInCartons": 10,
"unitCost":4.52,
"packSize":10,
"secondaryCategory":"Chairs"
}
]
},
{
"recommendation":{
"currentLevel":79,
"maxLevel":100
},
"items":[
{
"id":"10870",
"title":"MELAMINE BOWL",
"category":"BOWLS",
"imageUrl":"http://localhost/img/001.jpg",
"unitsInCartons":6,
"unitCost":0.93,
"packSize":5,
"secondaryCategory":"Kids Home"
},
{
"id":"10820",
"title":"PP YUM YUM CUP",
"category":"CUPS/MUGS",
"imageUrl":"http://localhost/img/002.jpg",
"unitsInCartons":12,
"unitCost":0.7,
"packSize":25,
"secondaryCategory":"Kids Home"
}
]
}
]
};

var items = data.products.map(function (product) {
return product.items.map(function (item) {
return {
title: item.title,
category: item.category,
unitsInCarton: item.unitsInCarton,
unitCost: item.unitCost,
packSize: item.packSize,
};
});
});

items = [].concat.apply([], items);

console.log(items);

关于javascript - 在 Angular JS Controller 中遍历复杂的 JSON 数组并显示特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43513050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com