H
H
HiDiv2021-06-23 11:59:15
typescript
HiDiv, 2021-06-23 11:59:15

How to update an object based on field mapping?

I have been writing in js for a long time and always considered such a task to be trivial, but in typescript I have not been able to solve it for several days.
There is an object whose properties need to be updated

const dest = {
  a2: 'a-empty',
  b2: 'b-empty',
  c2: 'c-empty'
}

There is an object from which you need to take new values
const source = {
  a1: 'a-new',
  c1: 'c-new'
}

There is an object that contains default values ​​(if they are not in source)
const defs = {
  a2: 'a-def',
  b2: 'b-def',
  c2: 'c-def'
}

And finally, there is an object that sets the field mapping
const map = {
  a2: 'a1',
  b2: 'b1',
  c2: 'c1'
}


You need to update the fields of the desc object with the values ​​from the source object from the map table. If source does not have the desired value, then take the appropriate one from defs.

On js (as an option!) I would do it like this
for (const toKey in dest) {
  const fromKey = map[toKey];
  dest[toKey] = typeof source[fromKey] === 'undefined' ? defs[toKey] : source[fromKey];
}


It may not be the most beautiful or "ideologically correct option", but it works! I can’t understand how to do this in TypeScript, because I keep getting errors and comments from the IDE and the compiler...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-06-23
@HiDiv

Well, you can nabilosipedit something like this . The truth is not sure that there is no better option.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question