I have a data object with key-value pairs. The data object comprises 4 properties with corresponding values. However, when data is pulled from the API, it sometimes shows 2 or 3 properties like in the case below (If the data is not available for a certain property it will not show up in the object). I want to add back the missing properties to the same object as shown below.
Data Output
var obj = {
property1: 100
property2: 80
property3: 50
}
I want to check within the object if property4 exists. If not, then I can add it to the same object with a boolean value i.e. false
My code that checks all properties whether they are missing, but it is not working as expected
var obj = {
property1: 100,
property2: 80,
property3: 50
}
;
const property_1 = obj.hasOwnProperty('property1');
console.log(property_1);
const property_2 = obj.hasOwnProperty('property2');
console.log(property_2);
const property_3 = obj.hasOwnProperty('property3');
console.log(property_3);
const property_4 = obj.hasOwnProperty('property4');
console.log(property_4);
if (property_1 === false || property_2 === false || property_3 === false || property_4 === false) {
obj.property1 = false
obj.property2 = false
obj.property3 = false
obj.property4 = false
}
console.log(obj)
//Console Output
{
property1: false,
property2: false,
property3: false,
property4: false
}
My Expected Result is:
{
property1: 100,
property2: 80,
property3: 50,
property4: false // Does not exist, hence it is false
}
May I know where I am going wrong?
>Solution :
Your condition
if (property_1 === false || property_2 === false || property_3 === false || property_4 === false) {
is true if any of the properties were missing. Then you set all the properties to false, including the ones that already had values.
You could just use a series of if statement for each property:
if (!obj.hasOwnProperty('property1')) {
obj.property1 = false;
}
if (!obj.hasOwnProperty('property2')) {
obj.property2 = false;
}
...
But the simple way to do this is to merge the object with an object that contains all the properties.
var obj = {
property1: 100,
property2: 80,
property3: 50
};
const defaults = {
property1: false,
property2: false,
property3: false,
property4: false
};
obj = {...defaults, ...obj};
console.log(obj);