How to convert JSON object structure to dot notation?

后端 未结 3 1440
旧时难觅i
旧时难觅i 2020-12-16 01:42

I\'ve got a variable I\'m storing that will dictate what fields to exclude from a query:

excludeFields = {
  Contact: {
    Address: 0,
    Phone: 0
  }
}
         


        
3条回答
  •  没有蜡笔的小新
    2020-12-16 02:07

    This should be flexible enough for most needs:

    function dotNotate(obj,target,prefix) {
      target = target || {},
      prefix = prefix || "";
    
      Object.keys(obj).forEach(function(key) {
        if ( typeof(obj[key]) === "object" ) {
          dotNotate(obj[key],target,prefix + key + ".");
        } else {
          return target[prefix + key] = obj[key];
        }
      });
    
      return target;
    }
    

    Run on your excludesFields variable like so:

    dotNotate(excludeFields);
    

    It returns the current structure:

    { "Contact.Address" : 0, "Contact.Phone" : 0 }
    

    So you can even do, inline:

    things.findOne({}, {fields: dotNotate(excludeFields) })
    

    Or provide as a projection:

    var projection = { "fields": {} };
    dotNotate(excludeFields,projection.fields);
    things.findOne({}, projection);
    

    Works nicely at all depths and even with arrays in an essential way, unless you need operators like $push.

提交回复
热议问题