I am returning null if an array of objects has the same property values and is fine with the direct object properties. I am trying with nested object property values in the same array, but it is failing. Below is the code for the same.
const getNullOrUniquePropertyValue = (arrToCheck, keyName, includeFullObject = null) => {
const uniqueValues = [...new Set(arrToCheck.map((v) => v[keyName]))];
if (uniqueValues.size !== 1) {
return null;
}
return includeFullObject ? arrToCheck[0].includeFullObject : arrToCheck[0].keyName;
};
And I am calling above function like as below
getNullOrUniquePropertyValue(
spaces,
'designHubProjectSpaceTypeId'
)
I am getting results as null for the above function because designHubProjectSpaceTypeId is not the same in the array.
I am passing nested objects property like as below, and it is returning null for below condition even if the array has both same values.
getNullOrUniquePropertyValue(spaces, 'spaceGeometry.ceilingHeight')
and the space structure like this as below
"spaces": [
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some Id"
},
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some other Id"
}
]
Could anyone please let me know where I am doing wrong with the above code?
Many thanks in advance!!
CodePudding user response:
Some feedback:
v[keyName]
isn't going to work ifkeyName
is a string with a dot ("spaceGeometry.ceilingHeight"
), you'll have to split the string and lookup the value at each level manuallyuniqueValues
is an array not a set, so use.length
instead of.size
I made a simple function getNestedValue()
that uses reduce to extract a nested value from an object.
const spaces = [
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some Id"
},
{
"spaceGeometry": {
"ceilingHeight": 9
},
"designHubProjectSpaceTypeId": "some other Id"
}
];
const getNestedValue = (obj, path) => path.split(".").reduce((accum, key) => accum[key], obj);
const getNullOrUniquePropertyValue = (arrToCheck, keyName) => {
const uniqueValues = [...new Set(arrToCheck.map((v) => getNestedValue(v, keyName)))];
if (uniqueValues.length !== 1) {
return null;
}
return uniqueValues[0];
};
const result = getNullOrUniquePropertyValue(
spaces,
'spaceGeometry.ceilingHeight'
);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I omitted includeFullObject
from my example because it's not relevant to this particular issue, and I'm unclear what it's supposed to do. If you're having issues with that part too, let me know the details and I can help.