0

I have a global array that I declare as

var fileMappings = [];

I do some work, and add a row to the array like so:

fileMappings.push({ buttonNumber: number, audioFile: file });

if I do a JSON.stringify(fileMappings) I get this:

[{“buttonNumber”:”btn11”,”audioFile”:{0A0990BC-8AC8-4C1C-B089-D7F0B30DF858}},
{“buttonNumber”:”btn12”,”audioFile”:{2FCC34A6-BD1A-4798-BB28-131F3B546BB6}},
{“buttonNumber”:”btn13”,”audioFile”:{53A206EC-7477-4E65-98CC-7154B347E331}}]

How can I access the GUID for "btn11", etc?

2
  • 1
    fileMappings[0]["audioFile"] Commented May 21, 2014 at 2:22
  • 1
    May I suggest studying a language you'll be using? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -- this is fundamentals 101 and easily findable. Commented May 21, 2014 at 2:26

2 Answers 2

2

Since Javascript arrays don't have support for keys, I would suggest that you use an object. Otherwise, you have to iterate through the entire array every time to look for the desired key.

var fileMappings = {};

And instead of push(), define a new property :

fileMappings[number] = { buttonNumber: number, audioFile: file };

This way, you can access your object with fileMappings['btn11']

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

Comments

1

You can iterate over the array's members to find the button, then return its GUID:

function findGUID(arr, buttonNumber) {
  for (var i=0, iLen=arr.length; i<iLen; i++) [
    if (arr[i].buttonNumber == buttonNumber) {
      return arr[i].audioFile;
    }
  }
  // return undefined - buttonNumber not found
}

Or if you want to use ES5 features:

function getGUID(arr, buttonNumber) {
  var guid;
  arr.some(function(obj) {
             return obj.buttonNumber == buttonNumber && (guid = obj.audioFile);
           });
  return guid;
}

but I think the first is simpler and easier to maintain.

Comments

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.