0

I have array:

aFrmsTbFields.push(["e7" , ["aaa", "bbb", "ccc"]]);
aFrmsTbFields.push(["e8", ["ddd", "eee", "fff"]]);
aFrmsTbFields.push(["e9", ["xxx", "yyy"]]);

I want to get ["xxx", "yyy"] array by e9 identifier.

How I can do it in JavaScript?

I have tried:

aXXXYYY = aFrmsTbFields["e9"];

But it doesn't work. I already know that arrays in JS are a bit diffrent than arrays in PHP.

I could create object, but im afraid I'm too bad in Javascript to handle them. I'm using array.forEach() a lot and I need to run something like this later:

aXXXYYY.forEach(...) // loop on ["xxx", "yyy"] array
Kamil
  • 13,363
  • 24
  • 88
  • 183
  • 5
    Use an object instead of array: `var fields = { "e7": ["aaa", ...], "e8": ["ddd", ...], "e9": ["xxx", ...] }; var e9 = fields["e9"];` – Andreas Jan 18 '16 at 17:16
  • You might find [this post](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) of interest. – user5325596 Jan 18 '16 at 17:18

2 Answers2

3

Just use filter method on Array object:

aFrmsTbFields.filter(function(arr) { return arr[0] === 'e9' })[0][1]

You may even wrap this into a function:

var findByFirst = function(arrayOfArrays, item) {
    return arrayOfArrays.filter(function(a) { return a[0] === item; })[0][1];
};

How it works, first filter returns only these array elements for which predicate returns true in our case arrays that have 'e9' as 0th element. Then we get first of these array (we expecct only one here) in our case ['eq', ["foo", "bar"]] then we access second element of that array by using [1] index, that will be ["foo", "bar"].

As other answers suggested object whould be much more useful here:

var obj = { 
  'e1': ['a', 'b'],
  // ... 
};

obj['e1'] // returns ['a', 'b']

Thanks Rick Hitchcock for spotting error.

csharpfolk
  • 4,124
  • 25
  • 31
2

I'm pretty sure you want to use an object.

aFrmsTbFields.e9 = ['xxx', 'yyy'];
console.log(aFrmsTbFields.e9);

Edit: There's no such thing as being "too bad" at a language. Just means you have more to learn. If you absolutely need to iterate through an object, you can use a for..in loop.

for (var fieldName in aFrmsTbFields) {
  // fieldName == e7 or e8 or e9 etc.
  var array = aFrmsTbFields[fieldName]; // ['xxx', 'yyy'];
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91