0

In my app there is the following data in a .json config file:

"directions": {
  "horizontal": [
    "left",
    "right"
  ],
  "vertical": [
    "down",
    "up"
  ]
}

In the app logic, the user selects one of the 4 specific directions (left, right, up, down) from a picker and then the word "horizontal" or "vertical" needs to be displayed in a label based on which option the user chose. So far, I have this code:
{{ specificDirection == 'right' ? 'horizontal' : 'other' }}
which verifies that the label displays the correct info when the user selects right. However, I'm at a loss for how to search the directions object in the .json file to find the specific direction in order to get the higher level direction to display in the label. Is it possible to do this without restructuring the JSON object?

1 Answer 1

1

One approach might be something like

const directions = {
    "horizontal": [
      "left",
      "right"
    ],
    "vertical": [
      "down",
      "up"
    ]
};

const queryDirection = "down";
const label = Object.keys(directions)
                .filter(function(lbl) { 
                  return directions[lbl].indexOf(queryDirection) > -1
                })[0];
console.log(queryDirection, '=>', label);

This assumes you can guarantee that the query direction will appear in the directions list. Otherwise you will need some safety checking.

Sign up to request clarification or add additional context in comments.

6 Comments

How would this be accomplished with the structure as const directions = {...?
Just use Object.keys(directions) in that case. I updated my answer with this approach.
I added this code to the created() hook (this is a Vue Native app). A console error has popped up: "[Vue warn]: Error in created hook: TypeError: directions[lbl].contains is not a function."
Edited to use indexOf instead
Looks like I got too used to writing in lambdas; needed to add a return statement. Works okay in the test I just ran. Hopefully that fixes it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.