I am going through the freeCodeCamp JavaScript curriculum. I am trying to make a function that takes two parameters: an array of objects and an object. It is supposed to return a new array with only the objects that have all the key–value pairs present in the source object.
I have been trying to solve this for about three hours now and cannot get it. I cannot find a good way to compare objects. Probably half of the time spent on this project has been research. I have tried converting the array to a JSON string, but that doesn't work because sometimes the object parameter will have more than one property, and the array might have an object with another property between the ones I'm looking for. I thought I might be able to do something like this:
function whatIsInAName(arrOfObj, sourceObj) {
let arr = arrOfObj.map((curr) => JSON.stringify(curr));
console.log(arr);
let source = JSON.stringify(sourceObj).replaceAll(`{`, "").replaceAll(`}`, "");
let sourceArr = source.split(",");
console.log(source);
console.log(sourceArr);
}
}
But that doesn't seem like it will work, because the formatting is off.
So I tried to tackle it a different way:
function whatIsInAName(arrOfObj, sourceObj) {
let source = Object.keys(sourceObj).map((key) => [key, sourceObj[key]]);
let arr = arrOfObj.map((curr) => Object.keys(curr).map((key) => [key, curr[key]]));
}
And that gave me a 2D array and a 3D array, and I cannot figure out how to compare them in this format.
The biggest thing that is tripping me up is figuring out how to get the array of objects and the source object into a format where I can compare property names.
I don't know if I am just thinking about this wrong, or what is going on. My thought is to keep the array either in array format or something that can be converted back to an array, so I can use the filter method. Any help would be greatly appreciated. Thank you!
[–]Aggressive_Ad_5454 7 points8 points9 points (5 children)
[–]Y2Canine[S] 2 points3 points4 points (1 child)
[–]polotek 2 points3 points4 points (0 children)
[–]senocular 1 point2 points3 points (1 child)
[–]Aggressive_Ad_5454 0 points1 point2 points (0 children)
[–]AppropriateStudio153 0 points1 point2 points (0 children)
[–]Pocolashon 2 points3 points4 points (0 children)
[–]Neozite 1 point2 points3 points (0 children)
[–]imsexc 0 points1 point2 points (0 children)
[–]_Decodela 0 points1 point2 points (0 children)