I encountered an object with multiple key names for one field.
Typically, objects in JavaScript have only a single key for each property. It is not possible for a JavaScript object to have multiple keys pointing to the same property value. (Although it is feasible to create aliases for properties, this is a different concept.)
You mentioned in a comment:
I'm attempting to access a value using a single key, is there a way to parse it somehow? The key I am referring to is TOTAL.
To retrieve the value associated with the key "TOTAL," you can first identify the actual property name and then use bracket notation to access the corresponding value:
const name = Object.keys(obj.formValues).find(name => name.includes("TOTAL"));
if (name) {
console.log(obj.formValues[name]); // "100"
}
However, if there are multiple properties containing "TOTAL" in the name, there is no guarantee of which one will be returned. (While object properties now maintain order, the ordering of properties with complex names like those in your object depends on their creation sequence, which should not be relied upon.)
Check out this live example:
const obj = {
formValues: {
"TOTAL;_null_;_null_;3;_null_": "100",
"billing;_null_;_null_;1;_null_": "Y",
"billing;_null_;_null_;2;_null_": "Y",
"billing;_null_;_null_;3;_null_": "Y"
}
};
const name = Object.keys(obj.formValues).find(name => name.includes("TOTAL"));
if (name) {
console.log(obj.formValues[name]); // "100"
}
Alternatively, you can utilize Object.entries
to access both the name and value simultaneously (although this involves creating temporary arrays, which modern JavaScript engines handle efficiently):
const obj = {
formValues: {
"TOTAL;_null_;_null_;3;_null_": "100",
"billing;_null_;_null_;1;_null_": "Y",
"billing;_null_;_null_;2;_null_": "Y",
"billing;_null_;_null_;3;_null_": "Y"
}
};
const property = Object.entries(obj.formValues).find(([name]) => name.includes("TOTAL"));
if (property) {
const [name, value] = property;
console.log(`Name is ${name}, value is ${value}`);
}