Sto usando AngularJS. Ho un oggetto json come di seguito;
info = [
{
"name": "Tom",
"id": "111"
},
{
"name": "Sam",
"id": "222"
},
{
"name": "James",
"id": "333"
}
]
Voglio avere una funzione tale che quando aviene trovato il nome corrispondente, viene eseguita qualche azione (in questo caso, restituisce l'id corrispondente). In altre parole, se il nome corrispondente dell'input è "Tom", voglio restituire l'id "111" in base all'oggetto json sopra .
Ho scritto del codice per trovare un nome corrispondente.
$scope.getIdFromName = function()
{
angular.forEach(info, function(value, key)
{
//$scope.searchByName contains the name to be matched
if (key === "name" && value === $scope.searchByName)
{
//$scope.searchById is the id to be returned
$scope.searchById = key;
alert("found");
}
});
};
Dove è andato storto il codice? O è così sbagliato che è meglio essere completamente riscritto? Eventuali suggerimenti (non è necessario essere angularjs) saranno i benvenuti. Grazie mille.
risposte:
3 per risposta № 1Poiché info è una matrice di oggetti, la chiave sarà l'indice di ciascun elemento e il valore sarà l'intero oggetto in quell'indice. Ogni for dovrebbe apparire così:
angular.forEach(info, function(value, key)
{
//$scope.searchByName contains the name to be matched
if (value.name === $scope.searchByName)
{
//$scope.searchById is the id to be returned
$scope.searchById = value.id;
alert("found");
}
});