Skip to content

Instantly share code, notes, and snippets.

@viiiprock
Created November 9, 2017 04:00
Show Gist options
  • Select an option

  • Save viiiprock/ebb4ab17423e06955ae83989ed0c5488 to your computer and use it in GitHub Desktop.

Select an option

Save viiiprock/ebb4ab17423e06955ae83989ed0c5488 to your computer and use it in GitHub Desktop.
Object filters
const rawObject = {
a: "hello",
b: "world",
c: {
d: 'ordinary',
e: undefined
},
f: undefined,
g: null,
}
/*
* Flatten object
*/
const flattenObject = obj => {
return Object.keys(obj).reduce((returnObj, k) => {
if (Object.prototype.toString.call(obj[k]) === '[object Date]') {
returnObj[k] = obj[k].toString()
}
else if ((typeof obj[k]) === 'object' && obj[k]) {
const flatObject = flattenObject(obj[k])
Object.keys(flatObject).forEach(k2 => {
returnObj[`${k}.${k2}`] = flatObject[k2]
});
}
else {
returnObj[k] = obj[k]
}
return returnObj
}, {})
}
/**
* Filter by keys
* @param {object} inputObj
* e.g { 'a': 'val 1', 'b': 'val 2', 'c.d': 'val 3'}
* @param {array} Keys - Accept keys after filter is done ['a', 'c.d']
* @return {object} - Filtered object result
*/
const objKeysFilter = (inputObj, Keys) => {
return Object.keys(inputObj)
.filter(k => Keys.includes(k))
.reduce((obj, k) => {
obj[k] = inputObj[k]
return obj
}, {})
}
const dataInput = flattenObject(rawObject)
const Keys = ['a', 'b', 'c.e', 'f']
console.log(objKeysFilter(dataInput, Keys))
/**
* Filter by validation value
* @param {object} inputObj - none flatten object
* e.g { 'a': 'val 1', 'b': 'val 2', 'c.d': 'val 3'}
* @return {object} - Filtered object result
*/
const objValFilter = inputObj => {
return Object.keys(inputObj)
.filter(k => inputObj[k] !== undefined)
.reduce((obj, k) => {
if (typeof(inputObj[k]) === 'object' && inputObj[k]) {
const nestedObj = inputObj[k]
Object.keys(nestedObj).forEach(
k2 => nestedObj[k2] === undefined && delete nestedObj[k2]
)
}
obj[k] = inputObj[k]
return obj
}, {})
}
console.log(objValFilter(rawObject))
// use flatten object
const objValFilter2 = inputObj => {
return Object.keys(inputObj)
.filter(k => inputObj[k] !== undefined)
.reduce((obj, k) => {
obj[k] = inputObj[k]
return obj
}, {})
}
console.log(objValFilter2(dataInput))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment