我正在构建 deepFilterObject.js 实用函数。尝试了很多,没有一个有效。 我在过滤器之前的对象是这样的:
{
userId: '6501747e258044dcfcf8c765',
name: 'Morning workout',
exercises: [
{ exercise: 'Oblique Crunch', sets: [Array] },
{ exercise: 'Chest Fly (Dumbbell)', sets: [Array] },
{ exercise: 'Jump Squat', sets: [Array] }
],
metadata: {
evaluation: null,
type: 'realtime',
copy: false,
note: 'This is a note. (optional)',
estimatedDurationMinutes: 60,
description: 'Some description. (optional)',
dates: {
scheduled: 'Tue Aug 08 2023 10:55:56',
completed: null,
creation: 'Tue Aug 01 2023 12:51:35'
},
access: {
authorId: 'objectId',
type: 'public/private (ENUM)',
comments: [Array],
copies: 0
}
}
}
这是我的函数调用:
const filteredBody = deepFilterObject(object, 'name', 'exercises', 'metadata.evaluation', 'metadata.access.type');
我期望得到类似这个对象的结果:
{
userId: '6501747e258044dcfcf8c765',
name: 'Morning workout',
exercises: [
{ exercise: 'Oblique Crunch', sets: [Array] },
{ exercise: 'Chest Fly (Dumbbell)', sets: [Array] },
{ exercise: 'Jump Squat', sets: [Array] }
],
metadata: {
evaluation: null,
access: {
type: 'public/private (ENUM)',
}
}
}
这是我的实用程序的代码,我将其作为“deepFilterObject”导入到我的控制器中:
function createObjectFromNestedArray(inputArray, sourceObject) {
// Base case: If the input array is empty, return the sourceObject.
if (inputArray.length === 0) {
return sourceObject;
}
// Get the current key from the inputArray.
const [currentKey, ...remainingKeys] = inputArray[0];
// Check if the current key exists in the sourceObject.
if (sourceObject.hasOwnProperty(currentKey)) {
// If it exists, recursively call the function with the remaining keys and the existing object.
sourceObject[currentKey] = createObjectFromNestedArray(remainingKeys, sourceObject[currentKey]);
} else {
// If it doesn't exist, create a new object and attach it.
sourceObject[currentKey] = {};
// Recursively call the function with the remaining keys and the newly created object.
sourceObject[currentKey] = createObjectFromNestedArray(remainingKeys, sourceObject[currentKey]);
}
// Return the modified sourceObject.
return sourceObject;
}
function deepFilterObject(obj, ...allowedFields) {
console.log(obj);
// const newObj = {};
// Object.keys(obj).forEach(el => {
// if (allowedFields.includes(el)) newObj[el] = obj[el];
// });
const deepAllowedFields = allowedFields
.filter(allowedField => allowedField.split('.').length > 1)
.map(allowedField => allowedField.split('.'));
const finalObj = createObjectFromNestedArray(deepAllowedFields, obj);
// console.log(finalObj);
// return newObj;
}
module.exports = deepFilterObject;
如有任何帮助,我们将不胜感激!预先感谢!
我会这样做:
const object = {
userId: '6501747e258044dcfcf8c765',
name: 'Morning workout',
exercises: [
{ exercise: 'Oblique Crunch', sets: [Array] },
{ exercise: 'Chest Fly (Dumbbell)', sets: [Array] },
{ exercise: 'Jump Squat', sets: [Array] }
],
metadata: {
evaluation: null,
type: 'realtime',
copy: false,
note: 'This is a note. (optional)',
estimatedDurationMinutes: 60,
description: 'Some description. (optional)',
dates: {
scheduled: 'Tue Aug 08 2023 10:55:56',
completed: null,
creation: 'Tue Aug 01 2023 12:51:35'
},
access: {
authorId: 'objectId',
type: 'public/private (ENUM)',
comments: [Array],
copies: 0
}
}
}
const filteredBody = deepFilterObject(object, 'name', 'exercises', 'metadata.evaluation', 'metadata.access.type');
document.write(`<pre>${JSON.stringify(filteredBody, null, 4)}</pre>`)
function deepFilterObject(object, ...paths) {
// parse paths to get the path object
const pathObject = preparePathObject(paths)
// recursive function
function filterObject(obj, path) {
const newObject = {}
// for each entry in the path object
for (const [key, subPath] of Object.entries(path)) {
// get sub object from the original object
const subObj = obj[key]
// if the sub object is an object, but not null or array
if (typeof subObj === 'object' && subObj !== null && !Array.isArray(subObj)) {
// run recursion
newObject[key] = filterObject(subObj, subPath)
} else {
// else assign the object to the new object
newObject[key] = subObj
}
}
return newObject
}
return filterObject(object, pathObject)
}
// creates nested path object
function preparePathObject(paths) {
const obj = {}
for (const path of paths) {
const keys = path.split('.')
let current = obj
for (const key of keys) {
if (!(key in current)) {
current[key] = {}
}
current = current[key]
}
}
return obj
}