Dawid Dawid - 6 months ago 13
Node.js Question

Store an object with an array inside?

Is there a way to store an

object
with an
array[id] = "certain value"
, so that every single user has a list of favorite things ?

What I'm trying to achieve is having a data object with undefined values at first, and filling them in, so for example Jack and Sam could have an assigned favorite movie saved.

I tried something like this with no success:

Data.js:

module.exports = function() {
return {
favMovie: ""
}
};


App.js:

var person [] = data();

//1st person
person[811767132257839].favMovie = "Matrix";

//2nd person
person[107230716367889].favMovie = "Kill Bill";

//3rd person
person[973676332752239].favMovie = "Avatar";

...

console.log( "Favorite movie: " + person[id].favMovie );

Answer

It doesn't sound like you want any arrays at all, just objects.

// Create an object that we'll keep person objects in
var personData = {};

// Add a person object to it for person ID #123
personData[123] = {};

// Set person #123's favorite movie:
personData[123].favMovie = "Avatar";

// Add a different person; this time, we'll add the movie at
// the same time
personData[234] = {
    favMovie: "Matrix"
};

When using objects as maps like that, sometimes people create the objects using Object.create(null) to avoid them having any inherited properties (like toString and valueOf and constructor):

person[123] = Object.create(null);
person[123].favMovie = "Avatar";

In ES2015 (aka "ES6"), you might want to use a Map rather than an object for the map of people:

var personData = new Map();

...and then use set and get for the individual person objects.

If the individual person objects get complicated, you might use a constructor function and associated prototype for them, using either ES5 syntax:

function Person() {
    // ...
}
Person.prototype.doSomething = function() {
    // ...
};

...or ES2015 syntax:

class Person {
    constructor() {
        // ...
    }
    doSomething() {
        // ...
    }
}

Then creating them:

personData[123] = new Person();
// or if using Map
personData.set(123, new Person());

Side note: Even when we write them as numbers, the keys (property names) in objects are always strings (unless you use ES2015 Symbols, which you probably wouldn't here). In contrast, keys in an ES2015 Map can be anything. Key equality in Map instances is determined using the special "same value zero" algorithm (which is basically === except that NaN is equal to itself [whereas it isn't in ===]).