Home > Blockchain >  Javascript find and map values based on scheme throwing undefined
Javascript find and map values based on scheme throwing undefined

Time:11-19

I'm working with Javascript to build a mapping function, that, given a scheme should find the mapper's object's value within an application variable.

My attempt at doing this results in an undefined error and I'm trying to figure out what I need to change to make it work correctly, I've put together a JS fiddle that can be found here as well.

const application = {
  state: {
    outgoings: {
      credit: 0,
      food: 0
    }
  }
}

const mapper = {
  "AppFoodSpend": "outgoings.food",
  "AppCreditSpend": "outgoings.credit"
}

for (const field in mapper) {
    console.log(application.state[mapper[field]])
    // expected results should be credit 0 and food 0
}

For further context, I have an object called application which contains some fields, they may not always be in the same order. My mapper object contains some key/value pairs, and it's the value that I'd like to try and find in application. for for instance, my console log should be retrieving something like:

  • application.state.outgoings.food
  • application.state.outgoings.credit

They may not always be in this order, so I need to (on each iteration of the mapper) find the key in my application variable.

What do I need to change here?

CodePudding user response:

Strings like 'outgoings.food' are not valid to navigate a data structure. You could use some "lenses" lib or write something like this...

const mapper = {
  "AppFoodSpend": ["outgoings", "food"],
  "AppCreditSpend": ["outgoings", "credit"]
}

for (const field in mapper) {
    console.log(
        mapper[field].reduce(
            (ctx, path) => ctx[path],
            application.state
        )
    )
}
  • Related