Created
May 14, 2019 07:05
-
-
Save nelsonsequiera/13fa3431539da58f4ca8796e5aa533f3 to your computer and use it in GitHub Desktop.
js object leveller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports.objectLeveller = (obj, outputObj, outputPath) => { | |
var outputAccObj = outputObj || {}; | |
var outputAccPath = outputPath || []; | |
return Object.getOwnPropertyNames(obj).reduce(function (outputAccObj, key) { | |
outputAccPath.push(key); | |
if (typeof obj[key] === 'object' && !!obj[key]) { | |
objectLeveller(obj[key], outputAccObj, outputAccPath); | |
} else { | |
outputAccObj[outputAccPath.join('_')] = obj[key]; | |
} | |
outputAccPath.pop(); | |
return outputAccObj; | |
}, outputAccObj) | |
}; | |
var temp = ['a', 'b', 'c']; | |
var obj = { | |
'a': 1, | |
'b': 2, | |
'c': 3, | |
'd': 4 | |
}; | |
var em = {}; | |
temp.map(key => { | |
em[key] = obj.hasOwnProperty(key) ? obj[key] : ''; | |
delete obj[key]; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment