如何获取键名不固定的JSON特定元素及AngularJS ng-if批量判断
Hey there! Let's break down your two questions about JSON and AngularJS step by step:
When dealing with JSON objects where keys aren't fixed, the core idea is to iterate through all the keys and check each corresponding value against your target condition. Here are two practical approaches:
Iterate through top-level keys
UseObject.keys()to get an array of all the object's keys, then loop through each one to filter for your desired elements. For example:const dynamicData = { customer: {results: 2938, id: 9283}, bredesh: {results: 2938, id: 248}, // Any new keys added later will be automatically included newUser: {results: 456, id: 'a'} }; // Collect all elements where id equals 'a' const matchingElements = []; Object.keys(dynamicData).forEach(key => { const item = dynamicData[key]; if (item.id === 'a') { matchingElements.push(item); } }); console.log(matchingElements); // Returns all items that meet the conditionRecursive search for nested structures
If your JSON has deeper nested layers, write a recursive function to traverse every level of the object. This ensures you won't miss target elements hidden in nested keys.
First, a quick syntax fix: The responses object you shared has a small mistake — you used semicolons ; to separate properties in the nested objects, but JavaScript/JSON requires commas , instead. Here's the corrected version:
var responses = { customer : {results: 2938, id: 9283}, bredesh : {results: 2938, id: 248} };
Now, for the ng-if challenge: AngularJS templates don't support directly iterating through dynamic object keys in ng-if expressions. The cleanest solution is to create a helper function in your controller that checks if any element in responses has an id of 'a', then call that function in your template.
Here's how to implement it:
- Add this function to your AngularJS controller:
$scope.hasMatchingId = function() { // Loop through all keys in the responses object for (const key in $scope.responses) { // Skip inherited properties from the prototype chain if ($scope.responses.hasOwnProperty(key)) { if ($scope.responses[key].id === 'a') { return true; // Return immediately once a match is found } } } return false; // No matches found };
- Update your template to use this helper function:
<div ng-if="hasMatchingId()" class="form-group"> <!-- Your content to display goes here --> </div>
This setup will automatically handle any new keys added to responses later — the function will check every element, so you don't need to modify the template every time you add a new entry.
内容的提问来源于stack exchange,提问作者Youssef Dahmane Jdid

