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
Untested, but this is roughly the approach I would take. Also reduces the complexity quite a bit.
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.
Caveat – this might have false-positives if any of the object values are
null
I think this code can help you with what you need (uppercase or lowercase letters are also taken into account):