lz430
lz430

Reputation: 135

How can I compare a string to an object key and get that key's value?

I want to do something relatively simple, I think anyways.

I need to compare the pathname of page with an object's kv pairs. For example:

if("pathname" === "key"){return value;}

That's pretty much it. I'm not sure how to do it in either regular Javascript or jQuery. Either are acceptable.

You can see my fiddle here: http://jsfiddle.net/lz430/2rhds1x3/

JavaScript:

var pageID = "/electrical-electronic-tape/c/864";
var pageList = [{
    "/electrical-electronic-tape/c/864": "ElectronicTape",
    "/industrial-tape/c/889": "IndustrialTape",
    "/sandblasting-tape/c/900": "SandblastingTape",
    "/Foam-Tape/c/875": "FoamTape",
    "/double-coated-d-c-dhesive-tape/c/872": "DCTape",
    "/Adhesive-Transfer-Tape/c/919": "ATTape",
    "/Reflective-Tape/c/884": "ReflectiveTape",
    "/custom-moulding": "CustomMoulding",
    "/request-a-quote": "RequestQuote"
}];
var label = pageID in pageList;
$('.el').html(label);

Upvotes: 1

Views: 1946

Answers (2)

caasjj
caasjj

Reputation: 1363

It depends kinda on the logic you want to implement. If you want to say "if object has the key, then do X, and if not, then do Y", then you handle that differently than "set label to the object's key's value if the key is there, or else set it to undefined or something else".

For the first case you do:

if (pageList.hasOwnProperty(pageID) ) {
  label =  pageList[pageID];
}
else {
  // do whatever, maybe some error?
}

For the second case, you can just say

 var label = pageList[pageID] || 'notFound';

As indicated by @Pointy, either get rid of the array or subsiture pageList[0] for pageList and pageList[0][pageID] for pageList[pageID] above, if you need to keep the array.

Upvotes: 0

Pointy
Pointy

Reputation: 413866

First, your "pageList" should just be a plain object, not an object in an array:

var pageList = {
    "/electrical-electronic-tape/c/864": "ElectronicTape",
    "/industrial-tape/c/889": "IndustrialTape",
    "/sandblasting-tape/c/900": "SandblastingTape",
    "/Foam-Tape/c/875": "FoamTape",
    "/double-coated-d-c-dhesive-tape/c/872": "DCTape",
    "/Adhesive-Transfer-Tape/c/919": "ATTape",
    "/Reflective-Tape/c/884": "ReflectiveTape",
    "/custom-moulding": "CustomMoulding",
    "/request-a-quote": "RequestQuote"
};

Then you can set "label" to the value from the mapping:

var label = pageList[pageID] || "(not found)";

That last bit of the statement above will set the label to "(not found)" if the lookup fails, which may or may not be applicable to your situation.

Upvotes: 5

Related Questions