我正在尝试搜索一个json对象来选择一些值。例如,我有一个值为'product-2‘的变量,我想查看json对象并返回'product-2’的attributes数组。
{
"attributes": [
...
],
"portfolio": [
{
"conn": [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here"
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
}
]有人能告诉我我如何做到这一点吗?谢谢
编辑:
根据Pramods的请求,我使用了下面的js (虽然这真的是错误的,但我确信)
$scope.productAttributes = [];
$scope.getProductDetails = function (product_id) {
console.log(product_id);
//search trough json
angular.forEach($scope.listOfProducts.product_id, function(value, key) {
// I was thinking I could loop through the json and when I find the matching product, then push its attributes into an array?
// if (key === enteredValue) {
// $scope.productAttributes.push({atribute: key});
// }
});
};编辑2
JSON结构已更改
发布于 2015-02-13 16:09:21
使用筛选器来对数组进行析构。
在我的示例中,我在Controller中使用了一个过滤器。这可能应该在服务或视图中完成。为了简洁起见,我在控制器中使用了过滤器。
过滤器表达式本质上说,返回数组中的第一个对象,其中包含一个属性“product”,即“Product-2”。
var app = angular.module('app', []).controller('MyController', MyController);
MyController.$inject = ['$filter'];
function MyController($filter) {
var data = [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
this.product = $filter('filter')(data, {product: "product-2"})[0];
}<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController as vm">
Product-2: {{vm.product}}
</div>
</div>
发布于 2015-02-13 14:00:10
如果您不知道product-2将如何嵌套,并且实际上需要搜索它,那么您需要进行递归搜索。递归函数是一个调用自己的函数。
这意味着迭代每个键,如果键是一个对象,也调用该键上的递归函数,直到找到您想要的键。
下面是一个类似的问题,为在JavaScript:traversing through JSON string to inner levels using recursive function中对JSON结构执行递归搜索提供了一些算法
发布于 2015-02-13 15:05:08
我认为你的JSON是错的,所以请纠正它
正确的JSON
{
"attributes": [],
"portfolio": [
{
"conn": [
{
"product-1": {
"label": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
},
{
"product-2": {
"label": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
}
]
}
]
}为了解析上面的json并返回产品信息,下面是代码
$(document).ready(function() {
$.each(dict['portfolio'][0], function(key, list){
$.each(list, function(index, value){
$.each(value, function(product, info){
if (product == "product-2"){
answer = {}
answer[product] = info;
return JSON.stringify(answer);
}
});
});
});
});小提琴连接:-
http://fiddle.jshell.net/2t8uknkc/
https://stackoverflow.com/questions/28499350
复制相似问题