I tried comparing data from each table from my data base but i failed I'm not too familiar with react, I'm still working on it, I'm trying to compare the data from recommendation and customization and if they are the same I display them.
const getRecommendation = () => {
Axios.get("http://localhost:5000/recommendations").then((response) => {
setRecomList(response.data);
});
};
const getCostumization = () => {
Axios.get("http://localhost:5000/customizations").then((response) => {
setCustomList(response.data);
});
};
const getRecById = async (id) => {
Axios.get(`http://localhost:5000/recommendations/${id}`).then((res) => {
setRecById(
recById.filter((val) => {
return val._id === id;
})
);
});
};
useEffect(() => {
{
recommendation.map((rec, i) => {
customization.map((cus, j) => {
if (
rec.type === cus.type &&
rec.violonBody === cus.violonBody &&
rec.violonStick === cus.violonStick &&
rec.violonChincrest === cus.violonChincrest
) {
getCostumization();
}
});
});
}
});
Thank you!
CodePudding user response:
Comparing objects & array is not an easy task to do by ourselves since it involves doing deep comparison.
One of the popular and convenient way is to use the _.isEqual from the lodash library.
You could use it like this:
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
CodePudding user response:
Could you do something like this? This should return an array of objects that are found in both arrays:
function compareArrays(arr1, arr2) {
const same = [];
for (const i = 0; i < arr1.length; i ) {
for (const j = 0; j < arr2.length; j ) {
if (arr1[i].name === arr2[j].name) {
same.push(arr1[i]);
}
}
}
return same;
}
So using your example it would look like this:
const getRecommendation = () => {
Axios.get("http://localhost:5000/recommendations").then((response) => {
setRecomList(response.data);
});
};
const getCostumization = () => {
Axios.get("http://localhost:5000/customizations").then((response) => {
setCustomList(response.data);
});
};
const getRecById = async (id) => {
Axios.get(`http://localhost:5000/recommendations/${id}`).then((res) => {
setRecById(
recById.filter((val) => {
return val._id === id;
})
);
});
};
useEffect(() => {
const equalPairArray = compareArrays(recommendation, customization)
if(equalPairArray.length > 0){
getCostumization();
}
});
CodePudding user response:
You can use like below
const compare = (obj1, obj2) => {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every((key) => obj1[key] === obj2[key]);
};
console.log(compare({ a: 1, b: 2 }, { a: 1, b: 2}));
console.log(compare({ a: 1, b: 2 }, { a: 1, b: 2, c:3 }));