Last active
December 27, 2020 23:15
-
-
Save ahmehri/6a720bbcaca5f82315522b62bbec2f9c to your computer and use it in GitHub Desktop.
How to convert an object of elements to an array without losing the object keys
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
const mapValues = require("lodash.mapvalues"); | |
// How to convert an object of elements to an array without losing the object | |
// keys? | |
// e.g going from | |
// { | |
// "attr-enum-sfa": { mode: "UPDATE", value: undefined }, | |
// "attr-set-enum-sfa": { mode: "ADD_VALUES", value: undefined }, | |
// "attr-text-sfa-s": { mode: "UPDATE", value: undefined } | |
// } | |
// to | |
// [ | |
// { name: "attr-enum-sfa", mode: "UPDATE", value: undefined }, | |
// { name: "attr-set-enum-sfa", mode: "ADD_VALUES", value: undefined }, | |
// { name: "attr-text-sfa-s", mode: "UPDATE", value: undefined } | |
// ]; | |
// keys are the name properties | |
let result; | |
const selectedAttributes = { | |
"attr-enum-sfa": { mode: "UPDATE", value: undefined }, | |
"attr-set-enum-sfa": { mode: "ADD_VALUES", value: undefined }, | |
"attr-text-sfa-s": { mode: "UPDATE", value: undefined } | |
}; | |
// using lodash | |
// this is not the way to go because the need to use an intermediate variable | |
// for readability purpose | |
const intermediate = mapValues(selectedAttributes, ({ value, mode }, key) => ({ | |
mode, | |
value, | |
name: key | |
})); | |
result = Object.values(intermediate); | |
// [ | |
// { mode: "UPDATE", value: undefined, name: "attr-enum-sfa" }, | |
// { mode: "ADD_VALUES", value: undefined, name: "attr-set-enum-sfa" }, | |
// { mode: "UPDATE", value: undefined, name: "attr-text-sfa-s" } | |
// ]; | |
// not using lodash | |
// this is the way to go, simple, readable and no intermediate variables | |
result = Object.entries(selectedAttributes).map(([name, { mode, value }]) => ({ | |
name, | |
mode, | |
value | |
})); | |
// [ | |
// { name: "attr-enum-sfa", mode: "UPDATE", value: undefined }, | |
// { name: "attr-set-enum-sfa", mode: "ADD_VALUES", value: undefined }, | |
// { name: "attr-text-sfa-s", mode: "UPDATE", value: undefined } | |
// ]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment