im looking on how you can use an object in an array using a "name" instead of a number.

this would be just like a DataTable where you can use the tables name instead of its position in the array.

anyone have an idea how this is done? or am i looking past something simple?

Dani AI

Generated

wanted named lookup instead of numeric indices; suggested a custom wrapper and pointed out collection concepts in other platforms. In JavaScript, the simplest, safest choices today are either plain objects (for string-keyed maps) or the ES6 Map (for arbitrary-key maps). Using Array['name'] merely creates a property on the array object — it is not a numeric index and most array APIs ignore it.

Practical examples:

// plain object (good for JSON interchange and simple string keys)
const dict = { users: { id: 1, name: 'Alice' } };
console.log(dict['users']); // { id: 1, name: 'Alice' }

// ES6 Map (preserves insertion order, accepts non-string keys)
const m = new Map();
m.set('users', { id: 1, name: 'Alice' });
console.log(m.get('users')); // { id: 1, name: 'Alice' }

// array with a named property — NOT an indexed element
const arr = [];
arr['users'] = { id: 1 };
console.log(arr.length); // 0 — numeric length unaffected
console.log(arr['users']); // the property exists but isn't an array element

Notes and pitfalls: forEach, map and other array methods iterate numeric indices only; named properties on arrays show up in for...in but that has its own pitfalls. Plain objects serialize nicely with JSON.stringify, while Map must be converted (for example JSON.stringify([...m])). Use Object.create(null) if inherited properties (like toString) are a concern. Map is part of ES6 (2015) — older environments need a polyfill.

Useful references: Array, Map, Object.create, JSON.stringify.

Recommended Answers

All 3 Replies

the only way I can think of would be to create your own class.

the only way I can think of would be to create your own class.

Hi,

Is there any perticular reason to use the Array. In Array datastructure the objects are indexed based on the integer value.

If you want to store the Key-Value pairs,you can use the following objects provided by .Net framework under System.Collections and System.Collections.Specialized namespace.

HashTable
DictionaryBase
NameValueCollection
ListDictionary
HybridDictionary

Thanks,
Kedar.

Hash table is exactly what i wanted thanks alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.