0

Is there a way to convert Object.keys to vars can be destructured for other object ?

So if I have

let ob1 = { key1: 'value', key2: 'value2'}
let dictionary = { key1: 'super value', key2: 'other value' }

can do this

let { Object.keys(ob1) } = dictionary
nonyck
  • 69
  • 1
  • 13
  • 3
    Its not clear what you're trying to do. what output are you expecting? – Jamiec Jan 04 '22 at 13:39
  • Trying to dynamically get the values from the dictionary based on the keys ob ob1 and put them in separate variables – nonyck Jan 04 '22 at 13:42
  • 1
    @nonyck Dynamically named variables are never a good idea. Destructuring needs fixed targets. – Bergi Jan 04 '22 at 13:43
  • Duplicate of https://stackoverflow.com/questions/35939289/how-to-destructure-into-dynamically-named-variables-in-es6 – Oskar Hane Jan 04 '22 at 13:44
  • You're welcome, maybe you can reformat your question so we can vote to reopen it. Anyway, I've answered that as a question. – 0stone0 Jan 04 '22 at 13:51

1 Answers1

1

Use Object.assign and map()

let ob1 = { key1: 'value', key2: 'value2'}
let dictionary = { key1: 'super value', key2: 'other value' }

let res = Object.assign(...Object.keys(ob1).map(key => ({ [key]: dictionary[key] })));
console.log(res);
{
  "key1": "super value",
  "key2": "other value"
}
0stone0
  • 34,288
  • 4
  • 39
  • 64