I have one selected store object data. When I make one POST
request as return I get single object of data or arrays of data, it depends on postal code. One postal code have multiple of PickUp
points or single PickUp
point.
I want to create an Helper function based on the POST
request return data, If it does not match with my already selected store object data then return true else return else.
I don't know how to create helper function which is unpredictable, it can be single object or arrays with multiple object.
Here is my sample data. I want to compare the data with areaId
const selectedArea = {
areaId: "84ed84ad-81e3-49ed-absjsjjjs",
name: "New york restaurant",
address: {
city: "New York",
postalCode: "0012231",
street: "New jersy"
}
};
const newArea = [
{
areaId: "84ed84ad-81e3-49ed-absyay6w",
name: "Veg retaurant",
address: {
city: "Calfornia",
postalCode: "0018383",
street: "Calfornia"
}
},
{
areaId: "84ed84ad-sjsjjs",
name: "Indian restaurant",
address: {
city: "Calfornia",
postalCode: "001aas8383",
street: "Calfornia"
}
},
{
areaId: "84ed84ad-81e3-49sjsjjshq8q",
name: "Desi restaurant",
address: {
city: "Calfornia",
postalCode: "0011881",
street: "Calfornia"
}
},
{
areaId: "84ed84ad-sjsjj-ssks-msms",
name: "chinese restaurant",
address: {
city: "Calfornia",
postalCode: "02992",
street: "Calfornia"
}
}
];
const newArea =
{
areaId: "84ed84ad-81e3-49ed-absyay6w",
name: "Veg retaurant",
address: {
city: "Calfornia",
postalCode: "0018383",
street: "Calfornia"
}
}
;
const selectedAreaMatch = (selectedArea, newArea) => {
console.log({ selectedArea });
console.log({ newArea }); // it can be object or arrays
// if does not match return true
// if match return false
return true;
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
First of all newArea has been declared twice. If you'd like to compare the two areas by their areaId, you can do in your function:
const selectedAreaMatch = (selectedArea, newArea) => {
console.log({selectedArea});
console.log({newArea}); // it can be object or arrays
// if does not match return true
// if match return false
for (let i = 0; i < newArea.length; i ) {
if (newArea[i].areaId === selectedArea.areaId) {
return true;
}
}
return false;
};
CodePudding user response:
You can convert the object into an array with a single element and then compare:
const selectedAreaMatch = (selectedArea, newArea) => {
const areas = Array.isArray(newArea) ? newArea : [newArea];
return !!areas.find(area => JSON.stringify(area) === JSON.stringify(selectedArea))
};
The comparison is a little more complicated because an object with the same properties isn't necessarily equal in JavaScript. You could probably do what I've done above and convert the objects to a JSON string and compare. Or iterate through all the properties of the object and compare with those of the other.