How to convert JSON object structure to dot notation?

后端 未结 3 1433
旧时难觅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:26

    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.

提交回复
热议问题