Issue
I'm trying to read a value in a JSON constant in Typescript with Angular, but just for performance I don't know if there is a way to read with a property included in the framework (or if it exists another way to do better, of course). This is my JSON constant value:
const myConstant= {
data : [
{
key1: "5",
key2: "extract",
key3: "unique1"
},
{
key1: "5",
key2: "extract",
key3: "unique2"
},
{
key1: "5",
key2: "extract",
key3: "unique3"
}
]
};
This constant has exported in another TS file just for find the key3 value for validate this in a conditional.
validateInfo(cod:string){
for (var i = 0; i < myConstant.data.length; i++){
var obj = myConstant.data[i];
for (var key in obj){
var value = obj[key];
if (key== "key3"){
if (value == cod){
return true;
}
}
}
}
return false;
}
So my question is, There is a way to extract the "key3" Value without doing a loop? like
myConstant.find(data.key3,'unique3');
what is the reason? I am trying to hide a view in frontend in case an user has no allowed to access using the JSON info (true or false for the previous function):
<div class="ts-cntnr" *ngIf="allowedInfo" >
Solution
Obviously there is! There are many ways you can do what you are asking for, and a simpler one is to use some() which checks if there is at least one object with a key called key3
, returning a boolean result which is your desired output.
const myConstant = {
data: [{
key1: "5",
key2: "extract",
key3: "unique1"
},
{
key1: "5",
key2: "extract",
key3: "unique2"
},
{
key1: "5",
key2: "extract",
key3: "unique3"
}
]
};
console.log(myConstant.data.some(subData => Object.keys(subData).includes("key3")))
// UPDATE
console.log(myConstant.data.some(subData => Object.keys(subData).includes("key3") && subData["key3"] == "unique3"))
Answered By - Deepak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.