Help with a function

asher14
Tera Contributor

I need help with my 'return item.key && key.id == item.key;' line. I am required to return true then its keeps that object in keys, if return false, then it takes out that element from keys. How can I code that?

 

var getColor = function(item){
if(keys){
var keyColors = keys.filter(function(key){
return item.key && key.id == item.key;
});
return keyColors.length === 1 ? keyColors[0].color : {};
}
return '';
};

1 ACCEPTED SOLUTION

TEST12311
Mega Expert

To achieve the functionality you described, you can modify the getColor function to include the logic for adding or removing the element from the keys array based on the condition. Here's the updated function:

 

var getColor = function(item) {
  if (keys) {
    var keyColors = keys.filter(function(key) {
      return item.key && key.id == item.key;
    });

    if (keyColors.length === 1) {
      // Return the color of the matched key
      return keyColors[0].color;
    } else {
      // If no matching key found, add the item to keys array
      if (item.key) {
        keys.push({ id: item.key, color: 'some_default_color' });
      }
      // Alternatively, you can also return a default color or an empty object
      // return 'some_default_color';
      // return {};
    }
  }

  // Return an empty string or a default color if keys is not defined or empty
  return '';
};

 

View solution in original post

5 REPLIES 5

TEST12311
Mega Expert

To achieve the functionality you described, you can modify the getColor function to include the logic for adding or removing the element from the keys array based on the condition. Here's the updated function:

 

var getColor = function(item) {
  if (keys) {
    var keyColors = keys.filter(function(key) {
      return item.key && key.id == item.key;
    });

    if (keyColors.length === 1) {
      // Return the color of the matched key
      return keyColors[0].color;
    } else {
      // If no matching key found, add the item to keys array
      if (item.key) {
        keys.push({ id: item.key, color: 'some_default_color' });
      }
      // Alternatively, you can also return a default color or an empty object
      // return 'some_default_color';
      // return {};
    }
  }

  // Return an empty string or a default color if keys is not defined or empty
  return '';
};