-1

How to convert

{
  'summary': {
    'name': 'test1',
    'age': '12',
    'gender': 'M'
  },
  'address': {
    'line1': 'Line1 address test',
    'line2': 'Line 2 Adress test'
  }
}

to

{
  'summary.name': 'test1',
  'summary.age': '12',
  'summary.gender': 'M',
  'address.line1': 'Line1 address test',
  'address.line2': 'Line 2 Adress test'
}

in typescript?

spender
  • 117,338
  • 33
  • 229
  • 351
Renjith Krishnan
  • 2,446
  • 5
  • 29
  • 53
  • look at https://stackoverflow.com/questions/58434389/typescript-deep-keyof-of-a-nested-object – HTMHell Feb 09 '23 at 11:59
  • Please read the tag description before you use a tag. The JSON tag contains: _"Do not use this tag for native JavaScript objects or JavaScript object literals."_ Your question is unrelated to JSON. There is no JSON in your question. Why did you add the tag stringify? – jabaa Feb 09 '23 at 11:59

1 Answers1

1

The solution is the same as in Javascript, for example, you can recursively go through the object and collect the property keys at each stage:

const data = {
    'summary': {
      'name': 'test1',
      'age': '12',
      'gender': 'M'
    },
    'address': {
      'line1': 'Line1 address test',
      'line2': 'Line 2 Adress test'
    }
  }

const objectEntriesRecursive = (obj, kcol=[]) => Object.entries(obj).flatMap(([key, val]) => (
    val instanceof Object && !Array.isArray(val) ? objectEntriesRecursive(val, [...kcol, key]) : [[[...kcol, key].join('.'), val]])
)

console.log(Object.fromEntries(objectEntriesRecursive(data)))

If you use Typescript, the types would be

type KeyType = number|string|symbol
type ObjectEntriesRecursive = (obj: {[key: KeyType]: any}, kcol?: KeyType[]) => [string,any][]
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
  • I cooked up a similar approach https://tsplay.dev/mAJv8W using generator funcs (using `yield*` to stand in for `flatMap` here) – spender Feb 09 '23 at 14:01
  • 1
    @spender Oh, nice. I used generators in Python a lot, but never in JS. I like that even though they cannot be used in SO's "this is not your homework" one-liners, the resulting code is still not your homework, but it looks nicer. – Moritz Ringler Feb 09 '23 at 14:40
  • I suspect `flatMap` is considerably less "churny" w.r.t. object allocation etc. Recursive generators, although fun, can quickly get costly. – spender Feb 09 '23 at 16:19
  • @spender Interesting, I would have thought it is the other way round. While those list functions (arguably) look nice, they are very inefficient, with all the function invocations and array cloning. My guess would have been that generators are a compromise, where you still have the function invocation, but at least don't build new objects at every step. Can't find a benchmark at the moment, but I will look into that. Thank you for the heads-up! – Moritz Ringler Feb 09 '23 at 17:30