Search code examples
javascriptarraysfor-loopjavascript-objects

How to check if the input matches the value in an array of objects


this.wiredUserData =
  [
    {"result":
    {"fields":
    {"Id":{"value":"005xx000001X85BAAS"},
     "Username":{"value":"[email protected]"}}}}, 
    {"result":
    {"fields":
    {"Id":{"value":"005xx000001X7sHAAS"},
     "Username":{"value":"[email protected]"}}}}
  ]

const uid = "005xx000001X85B"

usernameData(uid) {
    if (this.wiredUserData) {
        this.wiredUserData.forEach(function (item) {
            let wiredUserId = item.result.fields.Id.value.slice(0, 15);
            console.log(wiredUserId, "wired");
            console.log(uid, "uid");
            let wiredUsername = item.result.fields.Username.value;
            if (uid === wiredUserId) {
                return wiredUsername;
            }
        });
    }
    return '';
}

I am attempting to return the username value (e.g. [email protected]) when the function is called if the uid and Id match.

Hi, I am looping over wiredUserData and getting an error Expected to return a value at the end of function. What am I missing here? Should I use another kind of for loop ?


Solution

  • You shouldn't use .forEach functional loop when you want to return something.

    Either you can do this

    function usernameData(uid) {
      if (!this.wiredUserData) return;
    
      let tempResult = '';
    
        for (const data of this.wiredUserData) {
          let wiredUserId = data.result.fields.Id.value.slice(0, 15);
          let wiredUsername = data.result.fields.Username.value;
          if (uid === wiredUserId) {
            tempResult = wiredUsername;
          }
        }
      
      return tempResult;
    }
    

    or this

    function usernameData(uid) {
      if (!this.wiredUserData) return;
    
        for (const data of this.wiredUserData) {
          let wiredUserId = data.result.fields.Id.value.slice(0, 15);
          let wiredUsername = data.result.fields.Username.value;
          if (uid === wiredUserId) {
            return wiredUsername;
          }
        }
      
      return '';
    }
    

    or this

    function usernameData(uid) {
      if (!this.wiredUserData) return;
    
        for (const data of this.wiredUserData) {
          if (data.result.fields.Id.value.slice(0, 15) === uid) {
            // use null aware operator for more checking 
            // like data.result.fields.Username?.value ?? '';
            // can use in other example of above as well.
            return data.result.fields.Username.value;
          }
        }
      
      return '';
    }
    

    Thanks, if anything else or it is still not working comment on it again.