Skip to content

Instantly share code, notes, and snippets.

@tofikhidayatxyz
Created March 10, 2022 01:02
Show Gist options
  • Select an option

  • Save tofikhidayatxyz/b4ff5d9021998fed7a660985ae6de539 to your computer and use it in GitHub Desktop.

Select an option

Save tofikhidayatxyz/b4ff5d9021998fed7a660985ae6de539 to your computer and use it in GitHub Desktop.
Dynamic Array and Object picker
// sample
/**
pick data from object and array
this.$pick(SOURCE)
this.$pick(SOURCE, DATA_TO_PIC, DATA_TO_PIC, DATA_TO_PIC)
this.$pick(SOURCE, [SOURCE, TRANFORM_FUNCTION])
this.$pick(SOURCE, [DATA_TO_PIC, NEW_NAME, TRANFORM_FUNCTION])
this.$pick(
data.data.meta_datas,
'id',
'type',
['content', 'detail'],
['language', (val) => languages.find((lg) => lg.id === val)]
)
**/
const dataPicker = (dts, dataToPic) => {
let finalData = {}
for (const dtp of dataToPic) {
if (Array.isArray(dtp)) {
if (dtp[1] && typeof dtp[1] === 'function') {
finalData[dtp[0]] = dtp[1](dts[dtp[0]])
} else if (dtp[2] && typeof dtp[2] === 'function') {
finalData[dtp[1]] = dtp[2](dts[dtp[0]])
} else {
finalData[dtp[1]] = dts[dtp[0]]
}
} else {
finalData[dtp] = dts?.[dtp] || null
}
}
return finalData
}
export default function (mainData, dataToPic) {
// to pic ['source', 'to', 'handler']
if (!Array.isArray(mainData)) {
return dataPicker(mainData, dataToPic)
}
return mainData.map((dts) => dataPicker(dts, dataToPic))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment