Skip to content

Instantly share code, notes, and snippets.

@neysidev
Created July 27, 2022 06:43
Show Gist options
  • Select an option

  • Save neysidev/bd4e14b9898d43d4b137934584984fdc to your computer and use it in GitHub Desktop.

Select an option

Save neysidev/bd4e14b9898d43d4b137934584984fdc to your computer and use it in GitHub Desktop.
function getFields(array, fields = []) {
return array.map(item =>
fields.length === 1
? item[fields[0]]
: new Array(fields.length).fill(null).map((_, i) => item[fields[i]])
)
}
// How to use?
const arr = [{ id: 1, name: "Steve" }, { id: 2, name: "Bill" }]
getFields(arr, ["id"]) // [1, 2]
getFields(arr, ["id", ["name"]]) // [[1, 'Steve'], [2, 'Bill']]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment