0

I want to create a datatype or object in javascript that I can access by both index and key, and also I want a length property that shows how many items are in datatype. Kinda like.. MyDataType[0].name="John" MyDataType[0].salary="over 1k"

So if I wrote: MyDataType['John'].salary //I should get "over 1k"

And if I wrote: MyDataType[0].salary //I should get also "over 1k"

And I would like to have: MyDataType.length //should return 1

Is this possible? I tried with Proxy and it worked perfect for the index/key part but it didnt have a length property. I tried with array and it had index and length but no access with key

Thanks guys and please help me

Ibrahim D.
  • 318
  • 4
  • 17
  • What should `MyDataType['John'].salary` do if more than one element has `.name = 'John'`? You could just use an array of objects so that access via index works "normally", and use the `.find()` method to select items by key name. – nnnnnn Nov 05 '17 at 02:32
  • @nnnnnn thank you for the fast reply, I am 100% sure that the collection will be unique. Plus I want to use the key with `[KEY]` only and not with `find()` – Ibrahim D. Nov 05 '17 at 02:42

1 Answers1

0

For anyone who is struggling like I was, I finally found the answer to this, big thanks to @Quickredfox here: https://stackoverflow.com/a/36511465/8816810

Well that's the code:

"use strict";
 var MyCollection = new Proxy(
[{
name: 'monkey',
 score: 50
}, {
    name: 'giraffe',
 score: 100
}, {
name: 'pelican',
score: 150
}, {
    name: 'ZZoo',
  score: 69
}], {
 get: function(obj, prop) {
  if (prop in obj) {
    // default behavior
    return obj[prop];
  }
  if (typeof prop == 'string') {

      if (prop == 'length') {
      return obj.sort(function(a, b) {
        return obj.length;
      });
    }    

   for (var i = 0; i < obj.length; i++) {
      var player = obj[i];
      if (player.name == prop) {
        return player;
      }
    }

    return;
  }

}
});

document.write(MyCollection.length);
Ibrahim D.
  • 318
  • 4
  • 17