Reputation: 2324
in my angularjs app I get JSON object from API. I have an input field, where I can input ID manually, and if an item with this ID exists, I need to change his property. I also store this ID to sessionStorage, so when user refresh page, he get value like before refresh.
Here is json from API where I need to change ON THE FLY property SHOW to true if exist
$scope.tableParams.data = [
{id: 1015, type: "ssss", show: false},
{id: 1016, type: "ssss", show: false},
{id: 1017, type: "ssss", show: false},
{id: 1018, type: "ssss", show: false}
]
Function for getting input value and store to session storage, and also change SHOW property
$scope.getIndex = function (indexOfRow) { //indexOfRow is passed data from input field
//here I want to change show to true for passed id
sessionStorage.setItem("indexOfOpenedRow", JSON.stringify(indexOfRow));
}
I try answer from here but not working for me
I also try this, but allways get undefined
function findId(array, id) {
var i, found, obj;
for (i = 0; i < array.length; ++i) {
obj = array[i];
if (obj.id == id) {
console.log(obj);
return obj;
}
}
return undefined; // <= You might consider null or undefined here
}
$scope.getIndex = function (indexOfRow) { //indexOfRow is passed data from input field
//here I want to change show to true for passed id
angular.forEach($scope.tableParams.data, function(key, value){
var result = findId(key.id, indexOfRow);
console.log(result);
});
sessionStorage.setItem("indexOfOpenedRow", JSON.stringify(indexOfRow));
}
Upvotes: 1
Views: 85
Reputation: 4267
Filter is the function you are searching for. As i understood your question by reading your code you want to compare an seperate ID with the ID in the JSON? If I am wrong commend here and I will edit the answer:
function findIDAndSetShowingTrue(array, id) {
return array.filter(curr=> curr.id === id).map(curr => ({...curr, show: true}));
}
Upvotes: 2