I have a field object that can contain only one of different properties with an id as a value.
const Field = {
// Field can contain
property1Id: 'someId',
// Or
property2Id: 'someOtherId',
// Or
property3Id: '...'
//...
};
I want to return the property name and it's value. The following works fine but feels a bit long. Anyway to reduce it / be more efficient.
const propertyName = Field.property1Id
? 'Property 1'
: someObject.property2Id
? 'Property 2'
: someObject.property3Id
? 'Property 3'
: 'Other';
const id = Field.object1Id
? Field.property1Id
: Field.property2Id
? Field.property2Id
: Field.property3Id
? Field.property3Id
: null;
console.log(propertyName, id)
Thanks.
If this is what you mean, every property name with property value is returned :)
const Field = {
// Field can contain
property1Id: 'someId',
// Or
property2Id: 'someOtherId',
// Or
property3Id: '...'
//...
}
let entries = Object.entries(Field);
entries.forEach(entry => {
console.log(entry)
})
Best approach
const Field = {
// Field can contain
property1Id: 'someId',
// Or
property2Id: 'someOtherId',
// Or
property3Id: '...'
//...
};
let i = 0;
for (const property in Field) {
i++
console.log('Property ' + i, Field[property]);
}
Output:
"Property 1" "someId"
"Property 2" "someOtherId"
"Property 3" "..."