How to get all values inside nested objects with dynamic keys without loops?

I have this code

mydata = {
  "time": {
    "33": {
      "1 d": "23",
      "2 d": "35"
    },
    "44": {
      "1 d": "12",
      "2 d": "45"
    }
  }
}

console.log(mydata["time"]["33"]["1 d"]);

I want to ask if there is a way to get all values of “1 d” without using loops ?

Hi @william1, not sure why you don’t want to use loops but the divine alternative would be recursion… e.g. using a generator:

function * getValues (source, search) {
  const [key] = Object.keys(source)

  if (key === undefined) {
    return
  }

  const { [key]: value, ...rest } = source

  if (key === search) {
    yield value
  }

  if (typeof value === 'object') {
    yield * getValues(value, search)
  }

  yield * getValues(rest, search)
}

console.log(...getValues(mydata, '1 d')) // 23 12
3 Likes

Thanks it is just for learning

You could also something like map() even though under the hood it is pretty much a loop. As m3g4p0p said, not sure why you want to avoid the loop but this can be something you can use too…

function getValues(data) {
  return Object.entries(data['time']).map(x => x[1]["1 d"]);
}

This would return an array of the values for the 1 d keys.

3 Likes

Yeah just to clarify @william1, with loop you mean a for construct specifically or any kind of iteration? A generator is inherently an iterator as well after all, but FWIW maybe something like this would come closest…

function getValues(source, search) {
  if (typeof source !== 'object') {
    return []
  }

  const [key, next] = Object.keys(source)
  const { [key]: value, ...rest } = source

  return [
    ...key === search ? [value] : getValues(value, search),
    ...next ? getValues(rest, search) : []
  ]
}
1 Like

One thing please I get

Object is of type 'unknown'

So I searched alot and tried

let val: any; 
//or
let val: unknown;
val = Object.entries();

but the error still exists, how I pass this error ?