简体   繁体   中英

Array with object keys in JavaScript

How can I create an array with keys as objects (instances of a class)?

I am trying to do something like:

const parent = {};

while (child !== undefined) {
    for (const element of list) {
        parent[element] = child;
    }
    child = child.next;
}

This is basically the idea; the code works if element is a string, but it doesn't work correctly if the element is an object.

If you're in an ES2015 Environment you can use a Map

It would look like this:

let parent = new Map();
while (child !== undefined) {
    for (const element of list) {
        parent.set(element, child);
    }
    child = child.next;
}

You can run the below proof in this codepen

let parent = new Map();
const KEY1 = {};
parent.set(KEY1, 'hello');
console.log(parent.get(KEY1)); // hello

const KEY2 = {};
parent.set(KEY2, 'world');
console.log(parent.get(KEY2));

parent.set('est', {a: 'a'});
console.log(parent.get('est'));

Or see it in action as a stack snippet

 (function($) { const ELEMENTS = { $h1: $('#hello'), $container: $('#container') }; let parent = new Map(); const KEY1 = {}; parent.set(KEY1, 'hello'); console.log(parent.get(KEY1)); // hello const KEY2 = {}; parent.set(KEY2, 'world'); console.log(parent.get(KEY2)); parent.set('est', { a: 'a' }); console.log(parent.get('est')); /** original code from question w Map **/ var list = []; // to prevent error let parenta = new Map(); let child; while (child !== undefined) { for (const element of list) { parenta.set(element, child); } child = child.next; } })(jQuery);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 class="hello"></h1> <div class="container"></div>

You can't. .toString() is called on anything passed to an object as a key before it's used as a key. This is part of the Javascript language specification.

You can however make Symbols object keys if you want, but Symbols only take strings as a parameter.

This does not work as the method toString() will be called return something like [object Object] for all the items.

Property names can only be strings, but they can be any string... You could just turn the object into a string, using JSON.stringify(element) but you won't be able to use the key value like the object, since it will only be a representation of it...

Another solution (maybe better?) is to have a function on your class that create a string representation of the object... Let's say your object is coming from the database, you could use the record ID. You could use some random string too for what it is worth.

I'd be able to give you a better solution if I knew why you want to store the object as the key to start with.

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