Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

javascript - How to convert JSON object structure to dot notation?

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

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

I need to convert this to a dot notation that will work with Mongo's findOne, e.g.:

things.findOne({}, {fields: {'Contact.Address': 0, 'Contact.Phone': 0}})

Just passing excludeFields does not work and results in an error, "Projection values should be one of 1, 0, true, or false"

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

Do I have to write my own function to convert from hierarchical structure to flat dot notation? Or is there some mechanism to do this in JavaScript that I'm not aware of?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" && obj[key] !== null ) {
      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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...