0

I'm trying to create a new object savedStyle, with key/values from the style object, without repeating the object keys:

const style = getComputedStyle(document.body);

const savedStyle = {
  position: style.position, // the repetition
};

Why? I think it's not ideal, a small typo like psition could lead to a broken code:

Object.assign(document.body, savedStyle);

Is there any way to save multiple values, with the same key of the original object?

EDIT: verbose way:

const { position } = style;
const savedStyle = { 
  position,
};
gremo
  • 47,186
  • 75
  • 257
  • 421
  • Put all the desired keys in an array and iterate it with forEach e.g. `['position','top'].forEach(k => savedStyle[k] = style[k])`? – Nick Sep 06 '22 at 08:28
  • Sure @Nick, but I was looking for a more elegant solution, thanks! – gremo Sep 06 '22 at 08:29
  • you want all keys/values from style? – Giorgi Moniava Sep 06 '22 at 08:30
  • 1
    What's wrong with `const savedStyle = style;` – Evert Sep 06 '22 at 08:30
  • `verbose way` would be the way I'd do it - either that or create a helper function that may be a little verbose but simple to use – Jaromanda X Sep 06 '22 at 08:30
  • @Evert because i don't want all the pairs. – gremo Sep 06 '22 at 08:32
  • @gremo `Object.keys(style).forEach` and `savedStyle[key] = style[key]`. not works with Symbol properties – Hao.Le Sep 06 '22 at 08:32
  • @gremo important detail! For loop or `filter` seems like the way to go. – Evert Sep 06 '22 at 08:33
  • I think there's a [proposal](https://github.com/rbuckton/proposal-shorthand-improvements) which would allow you to do `const savedStyle = {style.position}` as shorthand for `const savedStyle = {position: style.position}` which is what you could do now – Jaromanda X Sep 06 '22 at 08:46

0 Answers0