SubjectX
SubjectX

Reputation: 896

Named objects and collection of them

not sure how to ask tbh :)

I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.

Example: I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.

In PHP I would write:

$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;

and so on..

How do I do this with objects in JS?

var entities = {items:[], items_status: [], items_count: 0};

entities[entity_id].items.push(item)

How does one name his object for later access (via name or in my case, entity_id?)

This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S

I also tried this:

var entities = {};
var entity = {items:[], items_status: [], items_count: 0};

but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.

Halp :(

Upvotes: 0

Views: 181

Answers (4)

SidOfc
SidOfc

Reputation: 4584

You can use a regular javascript object to create the associative array you're looking for.

Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.

You can use numeric keys in JS and still access them with the [] square brackets.

It works like this:

var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}

JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.

Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:

console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'

JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.

The only downside to this is that you can't have duplicate keys. No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Upvotes: 0

Amit
Amit

Reputation: 46323

There are 2 types involved here: Objects & Arrays.

Arrays are simple and you're probably familiar with them from any other language:

var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead

alert(myArray[1]); // alerts the value 2

Note: arrays are actually objects, and can have non-index properties as well

You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.

Objects share the square brackets notation, but the purpose is different:

var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;

alert(myObject[1]); // alerts the value 2

// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4

// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5

// and lastly
alert(myObject.prop); // alerts the value 4

So while arrays are accessed by index, objects are accessed by property names.


As for your entities, it looks like an array of objects. Lets see how we can do that:

function Entity() {
  this.items = [];
  this.items_status = [];
  this.items_count = 0;
}

var entitites = [];

entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;

Or you can wrap insertion in a more elegant function:

Entity.prototype.insert(item, status) {
  this.items.push(item);
  this.items_status.push(status);
  this.items_count++;
}

entities[0].insert(4, 'excellent!');

Upvotes: 1

Shreyas
Shreyas

Reputation: 1462

Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.

var entities = {};
entities["1234"] = {
    "items" : [],
    "items_status" : [],
    "items_count" : 0
};

Upvotes: 1

Calimero
Calimero

Reputation: 4288

If you want to keep control of the indexes in your JS array you can do so by not using .push() :

var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};

Just replace 5 by your integer entity_id variable, and there you go.

Upvotes: 0

Related Questions