使用 Node.jsHow 是否可以从单独的配置文件中过滤 JSON 文档,该文件具有包含要保留的键的数组或对象?

Using Node.jsHow do I filter a JSON document from a seperate config file that has an array or object containing the keys to keep?

假设我有一个这样的 JSON 对象:

{“first”:”first value”,
“second”:”second value”,
“third”:”third value”}

我有一个这样的配置文件作为示例:

{“filterList”:
{“first”: true,
“second”: false,
“third”: true}}

我想使用配置列表过滤掉错误的键并保留正确的键。配置结构只是一个示例,如果有更好的解决方案,我可以更改它。 我该如何在最佳实践中解决这个问题?

我们可以使用 require("filename") 或 JSON.parse(fs.readFileSync(file, 'utf8')) 加载配置文件,然后使用它来过滤对象 Object.entries 和 Array.reduce,像这样:

let configFile = 
{
    "filterList": {
        "first": true,
        "second": false,
        "third": true
    }
}

const originalObj = 
{
    "first": "first value",
    "second": "second value",
    "third": "third value"
}

console.log({ originalObj });

const filteredObj = Object.entries(originalObj).reduce((acc, [key, value]) => { 
    if (configFile.filterList[key]) {
        acc[key] = value;
    }
    return acc;
}, {})

console.log("Using Array.reduce:", { filteredObj } );

并使用@RickNs 的优秀建议 (Object.fromEntries):

let configFile = 
{
    "filterList": {
        "first": true,
        "second": false,
        "third": true
    }
}

const originalObj = 
{
    "first": "first value",
    "second": "second value",
    "third": "third value"
}

console.log({ originalObj });

const filteredEntries = Object.entries(originalObj).filter(([key, value]) => configFile.filterList[key])
const filteredObj = Object.fromEntries(filteredEntries)

console.log("Using Object.fromEntries:", { filteredObj } );