简体   繁体   中英

How to get a value from an array by name instead of key-number

I've created an object and added an asset b345 with some properties in it:

asset = [];
asset.push({'b345' : { 'prop1':'value 1', 'prop2': null}});

I want to push some more assets later, dynamicaly into the same asset-object. So that the asset object holds all assets generated in the code.

Later on in my code I want to retrieve the array associated with one of the entries via the unique identifier b345 . But that seems not to work.

asset['b345'];

But that results in an undefined . But If I try to get the data via asset[0] It returns the right object.

How could I arrange this container object asset so that I can
1- easliy add new objects
2- retrieve the object via the identifier?

ps: I found this: https://npmjs.org/package/hashtable but it is only usefull for large storage; and it says it can be done through objects only. But I can't find how it works :(

Instead of using an array you use an object

asset = {};
asset['b345'] =  { 'prop1':'value 1', 'prop2': null};

then asset['b345'] will give you { 'prop1':'value 1', 'prop2': null}

If you have no need to iterate through your list of objects in some consistent order, then you probably shouldn't make an array in the first place; just make an object:

var asset = {};
asset['b345'] = { 'prop1':'value 1', 'prop2': null};

If you do need to have both array behavior and key-lookup, an efficient way to do it would be to make an array and an object:

var assets = {
  list: []
, map: {}
, push: function(key, value) {
    map[key] = value;
    list.push({ key: value });
  }
};

Then:

assets.push('b345', { 'prop1': 'value 1', 'prop2': null });

Subsequently assets.list[0] will be { b345: { prop1: 'value 1', prop2: null }} and assets.map['b345'] will be {prop1: 'value 1', 'prop2': null} .

You'd want to make it a little more sophisticated to deal with updates properly, but that's the basic pattern.

There's many way to do this. To simply fix this problem:

var asset = new Object; // new object
asset['b345'] = {'prop1':'value 1', 'prop2': null}; // an object property = new object (wrapped in {})

Another way, is:

asset = {'b345' : { 'prop1':'value 1', 'prop2': null}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM