Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 37 additions & 9 deletions dotify.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,45 @@
'use strict';
// <https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?tab=readme-ov-file#_isplainobject>
function isPlainObject(value) {
if (typeof value !== 'object' || value === null) return false;

var ObjectID = require('bson-objectid');
if (Object.prototype.toString.call(value) !== '[object Object]') return false;

const proto = Object.getPrototypeOf(value);
if (proto === null) return true;

const Ctor =
Object.prototype.hasOwnProperty.call(proto, 'constructor') &&
proto.constructor;
return (
typeof Ctor === 'function' &&
Ctor instanceof Ctor &&
Function.prototype.call(Ctor) === Function.prototype.call(value)
);
}

// https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?tab=readme-ov-file#_isempty
const isEmpty = (obj) =>
[Object, Array].includes((obj || {}).constructor) &&
Object.entries(obj || {}).length === 0;

function dotify(obj) {
var res = {};
const res = {};
function recurse(obj, current) {
for (var key in obj) {
var value = obj[key];
var newKey = (current ? current + '.' + key : key); // joined key with dot
if (value && typeof value === 'object' && !(value instanceof Date) && !ObjectID.isValid(value)) {
recurse(value, newKey); // it's a nested object, so do it again
// eslint-disable-next-line guard-for-in
for (const key in obj) {
const value = obj[key];
const newKey = current ? current + '.' + key : key; // joined key with dot
if (
typeof value !== 'undefined' &&
(isPlainObject(value) || Array.isArray(value))
) {
if (Array.isArray(value) && isEmpty(value)) {
res[newKey] = value;
} else {
recurse(value, newKey); // it's a nested object, so do it again
}
} else {
res[newKey] = value; // it's not an object, so set the property
res[newKey] = value; // it's not an object, so set the property
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
"test": "./node_modules/.bin/istanbul cover --dir ./coverage ./node_modules/.bin/_mocha -- -R spec -t 10000 --recursive --slow 2"
},
"devDependencies": {
"mocha": "*",
"istanbul": "*"
"istanbul": "*",
"mocha": "*"
},
"keywords": [
"mongoose",
Expand All @@ -37,6 +37,5 @@
"dotify"
],
"dependencies": {
"bson-objectid": "^1.3.1"
}
}