'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?



Solution 1:[1]

I use a function pretty much similar to the accepted answer

    function convertJsonToDot(obj, parent = [], keyValue = {}) {
      for (let key in obj) {
        let keyPath = [...parent, key];
        if (obj[key]!== null && typeof obj[key] === 'object') {
            Object.assign(keyValue, convertJsonToDot(obj[key], keyPath, keyValue));
        } else {
            keyValue[keyPath.join('.')] = obj[key];
        }
    }
    return keyValue;
}

Here, I do an additional check 'obj[key] !== null' because unfortunately null is also of type 'object'.

I actually wanted to add this a comment to the accepted answer but couldn't because of not enough reputation.

Solution 2:[2]

var fields = {};
for (var k in excludeFields) {
  for (var p in excludeFields[k]) {
    fields[k + '.' + p] = excludeFields[k][p];
  }
}

Then:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 David Rosson