I have some code that will filter data to match a specified set of keys. So far, my code handles whether the data passed in is an array or an object of a specific kind. For example, a car object or an array of car objects, and the key list would be car attributes. However, I’ve just gotten a new dataset and I’m wondering the best way to go about handling it. Here is my code so far (don’t worry too much about my array/object validation, I have custom functions that do much more checking)
const goodDataObject = {
"make": "toyota",
"model": "rav4",
"color": "white"
"mileage": "10000",
"engine": "hybrid"
};
const goodDataArray = [
{
"make": "toyota",
"model": "rav4",
"color": "white"
"mileage": "10000",
"engine": "hybrid"
},
{
"make": "chevrolet",
"model": "cruze",
"color": "black"
"mileage": "20000",
"engine": "gas"
}
]
const badDataObject = {
"dealer": "John Does Cars",
"factory": "Michigan",
"cars": [
{
"make": "toyota",
"model": "rav4",
"color": "white"
"mileage": "10000",
"engine": "hybrid"
},
{
"make": "chevrolet",
"model": "cruze",
"color": "black"
"mileage": "20000",
"engine": "gas"
}
]
}
// -->> results from goodDataObject:
{
"make": "toyota",
"model": "rav4"
}
// -->> results from goodDataArray:
[
{
"make": "toyota",
"model": "rav4"
},
{
"make": "chevrolet",
"model": "cruze"
}
]
// -->> results I WANT from badDataObject:
{
"dealer": "John Does Cars",
"factory": "Michigan",
"cars": [
{
"make": "toyota",
"model": "rav4"
},
{
"make": "chevrolet",
"model": "cruze"
}
]
}
Here is my current code called with keys ["make", "model"]
.
function filterData(data, keys) {
let filtered = null;
if (typeof data === 'object') {
for (let x of keys) {
filtered[x] = data[x]
}
} else if (Array.isArray(data)) {
filtered = [];
for (let y of data) {
let filteredObject = {};
for (let key of keys) {
filteredObject[key] = y[key];
}
filtered.push(filteredObject);
}
}
return filtered;
}
I need to handle the badDataObject, and I’ve been thinking of a recursive option, but that has not been successful so far so I can’t post much there