Home > Blockchain >  Read a value key of a JSON constant in Typescript with Angular
Read a value key of a JSON constant in Typescript with Angular

Time:12-21

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  *ngIf="allowedInfo" >

CodePudding user response:

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"))

CodePudding user response:

you can try this code

  var item= findItem(myConstant.data, "key3","unique3");

function

function findItem(items, key,value) {
      const result = items.filter(function(item) {
       for (const property in item)
         if(property==key && item[property]==value) return item;
        });
       return result != undefined ? result[0] : null;
    };

result

{
  "key1": "5",
  "key2": "extract",
  "key3": "unique3"
}
  • Related