3 Replies Latest reply on Sep 12, 2016 12:23 PM by Marcos Vainer Loeff

    Accessing returned list of attributes by name rather than array index

    MaxStrueverWipro

      so this may be a unique issue, but, when I do a PI Web API call that returns, for example, all child elements or all child attributes, I find it a bit unusable to be returned just a simple of array, instead of an object that could be accessed by the attribute name.

      Example:

      values of all child attributes call:

      https://[server]/piwebapi/streamsets/[parentelementWebId]/value

      returns:

      1. Object {Links: Object, Items: Array[27]} where Items looks like:
        1. Items:Array[27]
          1. 0:Object
          2. 1:Object
          3. 2:Object
          4. 3:Object
          5. ...

       

      So, say I want to see just the value of the attribute named "Temperature"

      rather than being able to do obj.Items.Temperature (or obj.Items['Temperature'])

      I have to go through each item in the array, and check if .Name == "Temperature" 

      and then later if I need the attribute named "Calculation" from that same element, I'd have to again loop through the whole array.

       

      Am I missing a trick here to change the return type of Items from array to object?

       

      to solve my issue and get the array into the desired object format, I found a quick function that loops through all Items only once and returns the object with the Name as the keys

       

      function reformatAttrArray(arr) {
          var result = {};
          for (var i = 0; i < arr.length; i++) {
              result[arr[i].Name] = arr[i];
          }
          return result;
      }
      

      or a fancier version with array.reduce

       

      function otherReformat(arr){
          var obj = arr.reduce(function(obj,item){
              obj[item.Name] = item; 
              return obj;
          },{});
          return obj;
      }
      

       

      note, this assumes all Items in the array have a unique Name (and perhaps this is why OSIsoft chose to return the Items array like this), but this is already guaranteed to be the case if you are getting only the child attributes of a single AF Element

       

       

      let me know if I'm missing a trick to do this automatically with PI Web API,

      otherwise, maybe others will find these code snippets useful