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

Bert_c1
Kilo Patron

Hello asher14,

 

Where is that function defined, a client script, script include, ...?  It has several problems as posted.

 

var getColor = function(item){
	// 'keys' is not defined, null object
	if(keys){
		var keyColors = keys.filter(function(key){		// 'key' is not defined, null
			return item.key && key.id == item.key;
		});				// why is ')' present here?
		return keyColors.length === 1 ? keyColors[0].color : {};
	}
	return '';
};

 

Seems some review of Javascript is needed, a free training is here:

 

https://www.codecademy.com/catalog/language/javascript

 

asher14
Tera Contributor

Client Script

asher14
Tera Contributor

Here is the updated code so far

//returns the icon color and name associated with it
var getColor = function(item){
if(keys){
var keyColors = keys.filter(function(key){
return key.id === item;
});
return keyColors.length === 1 ? keyColors[0].color : {};
}
return '';
};

Bert_c1
Kilo Patron

Hi asher14,

 

My guess is a 'Catalog Client Script', if so (or not) what is the Type? onLoad, onChange, ... and for what table?  There are lots of working examples in your instance. And please post the entire script.  Then I believe Community members can help you.