skip to Main Content

I think my code can be smaller but idk how can I minimize it ?

How you would rewrite the code smaller ?

PS:

I get a JSON object and I have to find the key name from an value.

I have to found which color has the option key

exp:

option1: "blue"
option2: "S"

but if I get another request then it could be like that:

option1: "S"
option2: "blue"

so it can be reversed, so I have to find the key name from an color name

const getKeyByValue = (obj: _Variant, value: string) => Object.keys(obj).find(key => obj[key] === value.toLowerCase());

let k = null;

for(let i = 0; i < variants.length; i++) {
    k = getKeyByValue(variants[i], "schwarz");
      if(k) {
          break;
      }
     k = getKeyByValue(variants[i], "black");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "weiß");
      if(k) {
          break;
      }
     k = getKeyByValue(variants[i], "white");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "rot");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "red");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "gelb");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "yellow");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "grün");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "green");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "blau");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "blue");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "lila");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "purple");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "beige");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "pink");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "camouflage");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "gold");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "silber");
      if(k) {
          break;
      }
    k = getKeyByValue(variants[i], "silver");
      if(k) {
          break;
      }

3

Answers


  1. Untested, but this is roughly the approach I would take. Also reduces the complexity quite a bit.

    const germanColors = new Set(['schwarz', 'black', 'weiß', '...etc...']);
    
    for(let i = 0; i < variants.length; i++) {
    
      if (Object.values(variants[i]).find(
        variantVal => germanColors.has(variantVal)
      ) {
        break;
      }
    }
    
    Login or Signup to reply.
  2. First issue I see is that you’re using Object.keys() multiple times for the same object.

    Seems you would benefit from inverting the object (swapping keys for values) then finding the first match from your array of colours.

    const variants = [
      { option1: 'blue', option2: 'S' },
      { option1: 'S', option2: 'blue' },
    ];
    
    // blue is jumping the queue just for this demo
    const colours = ['schwarz', 'black', 'blue' /* etc */];
    
    let k;
    
    for (let i = 0; i < variants.length; i++) {
      const valueMap = Object.fromEntries(
        Object.entries(variants[i]).map(([k, v]) => [v, k]),
      );
      k = valueMap[colours.find((colour) => colour in valueMap)];
    
      if (k) {
        console.log(`Found a colour in variants[${i}].${k}`);
        break;
      }
    };
    
    console.log('k:', k);

    Caveat – this might have false-positives if any of the object values are null

    Login or Signup to reply.
  3. I think this code can help you with what you need (uppercase or lowercase letters are also taken into account):

    const variants = [
        {"S": "blue"},
        {"R": "red"},
        {"blue": "S"}
    ]
    
    function run(valueParam){
        const entries = Object.assign({}, ...variants);
        for (const [key, value] of Object.entries(entries)) {
            if (value.toLowerCase() == valueParam.toLowerCase()) {
                return key
            }
        }
    }
    
    let result = run("blue")
    console.log(result)
    
    result = run("red")
    console.log(result)
    
    result = run("BLUE")
    console.log(result)
    
    result = run("S")
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search