I am faced with a situation where I have an extensive array comprising approximately 1000 items. Depending on a certain condition, I only require specific fields from each object in the array to be extracted and mapped into a new, smaller array. The challenge here is that the required fields are dynamic, and I wish to avoid using a for loop within every iteration of the map function.
function extractFields(fieldsNeeded, data) {
//Looking for a way to quickly extract specified fields from the data without utilizing a for loop
return data.map((item) => {
const newItem = {};
for(const field of fieldsNeeded) {
newItem[field] = item[field];
}
return newItem;
}
}
let fieldsNeeded;
if(something) {
fieldsNeeded = ['a', 'c'];
} else {
fieldsNeeded = ['b', 'c'];
}
const data = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 }, { a: 7, b: 8, c: 9 }, { a: 10, b: 11, c: 12 } ];
const extractedData = extractFields(fieldsNeeded, data);