简体   繁体   English

如何检查 Json Doc 在 Node JS 中是否具有所有必需的键

[英]How to check if a Json Doc has all required Keys in Node JS

I found multiple examples on how to check a json file if a key exist's but i am trying to do this a bit more efficient.我找到了多个关于如何检查 json 文件是否存在密钥的示例,但我正在尝试更有效地执行此操作。

I have an import process where user uploads a csv file and then i convert it to json.我有一个导入过程,用户上传一个 csv 文件,然后我将其转换为 json。

As there is multiple formats in my case for the csv file i want to check if a certain set of fields / keys are present before i import since most of them have different key names.由于我的 csv 文件有多种格式,我想在导入之前检查是否存在一组特定的字段/键,因为它们中的大多数都有不同的键名。

So to start i go and count the Key count in the json which narrows down my possible definitions.所以开始我去计算 json 中的键数,这缩小了我可能的定义。 then i would like to use an array of keys which like然后我想使用一组喜欢的键

["field1", "field2", "field3"] 

and then check if all of them are in my json file.然后检查它们是否都在我的 json 文件中。 As there a simple way or will it require to loop thru array and check for each key ?因为有一种简单的方法还是需要循环遍历数组并检查每个键?

You can pull out the keys from your JSON object, but you still need to loop through the list of "required" keys and check that they exist in the list of keys.您可以从 JSON 对象中提取密钥,但您仍然需要遍历“必需”密钥列表并检查它们是否存在于密钥列表中。 Something like the following should do the trick:像下面这样的东西应该可以解决问题:

const myObject = {}; // getObjectFromCSV();
const required = ["field1", "field2", "field3"];
const objKeys = Object.keys(myObject);
required.every(key => objKeys.includes(key));

To get a list of the missing required fields, I'd do the following.要获取缺少的必填字段的列表,我会执行以下操作。 This code would replace the last line above (with the every with the following:这段代码将替换上面的最后一行( every带有以下内容:

const missingRequired = required.reduce(
  (acc, key) => { 
    if (!objKeys.includes(key)) { 
      acc.push(key);
    } 
    return acc;
  }, []);
const isValid = missingRequired.length === 0;

In the reducer function, acc is the accumulator set to [] initially, if it is empty, then there were no missing keys.在 reducer 函数中, acc是最初设置为[]的累加器,如果为空,则表示没有丢失的键。 Note that the condition is opposite compared to the every function, as we want to know when a key is missing, not if all of them are found.请注意,与every函数相比,条件是相反的,因为我们想知道何时缺少键,而不是是否找到了所有键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM