I have the following object
const someobj = {constantValues: {status: [{value: 1, key : "enabled"},{value: 0, key: "disabled"},{value: 3, key: "archived"}]}}
And the following key
const keyFilter = "status"
I try to filter the object with the value 3 from someobj, so i do
const constantValueIsNumber = typeof someobj.constantValues.status[0].value === "number" ? true: false
const val = someobj.constantValues[keyFilter].find(i => i.value === constantValueIsNumber? Number("3"): "3")
console.log(val) // {value: 1, key: "enabled"}
WHy is it returning 1, when im filtering 3 and it should return
{value: 3, key: "archived"}
This works for me.
const someobj = {constantValues: {status: [{value: 1, key : "enabled"},{value: 0, key: "disabled"},{value: 3, key: "archived"}]}};
const keyFilter = "status";
const valueToCheck = "3";
const val = someobj.constantValues[keyFilter].find(i => i.value.toString() === valueToCheck.toString());
console.log(val);
We convert all values to string so both numbers and strings work.
your predicate was not written correctly; you should place parenthesis to define the order of operations. The .find() method has to be something like this
const val = someobj.constantValues[keyFilter].find(i => i.value === (constantValueIsNumber? 3 : "3"))
it outputs:
val: {value: 3, key: 'archived'}