0

What is the best way, in Javascript, to use an array as a key that I can match against to get a value?

What I want to be able to do is get a value that may map to multiple keys.

Using a switch it would look like this:

switch(item)
{
    case "table": // fall through
    case "desk": // fall through
    case "chair": // fall through
        result = "office"
        break
}

in my head the syntax would be:

if (dict[0].key.contains(item)) return dict[0].value

I don't want to use a switch as the keys and values need to be dynamically allocated.

At the moment I am setting up an object which has two different arrays which need to stay synchronized in order to return the right values, which seems less than ideal.

var grammar =
[
{
    "app": "sms",
    "items":
    [
        [ "message","sms", "send"],
        [ "view", "read"]
    ],
    "terms":
    [
        [ "who+contact", "message+text" ],
        [ "who+contact"]
    ]
},
{
...
}
];

here if I get a match to "message" , "sms" or "send" I return "who+contact,message+text", if I get a match to "view" or "read" I return "who+contact"

Thanks for any ideas.

2 Answers 2

1

Why can't you just use a normal object?

var store = {
    "table":"office",
    "desk":"office",
    "chair":"office"
};

console.log(store["desk"]);

If the problem is duplication, you can make the value a reference type.

var office = {value:"office"};
var store = {
    "table":office,
    "desk":office,
    "chair":office
};
Sign up to request clarification or add additional context in comments.

Comments

1
var terms = [
    0           : [ "who+contact" , "message+text"],
    "whatever"  : [ "who+contact" ]
];

var items = [
    "message" : 0,
    "sms"     : 0,
    "send"    : 0,
    "view"    : "whatever",
    "read"    : "whatever"
];


function getTerm(match) {
    if (item[match]!==null) {
      return terms[ items[match] ];
    }
    return null;
}

1 Comment

It's not seeming like there is a better answer than this way, so I am going with this answer so far. Thank you.

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.