Array of email objects in Javascript - javascript

I need to use an array of emails whose each record should point to several attributes like To, From, and Subject. I did something like this:
var emailAttr = new Array("to","from","subject");
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2"; // This line gives exception that emails[1] is undefined
What am i missing and how can i make it work so that I can access elements like emails[i].to ?

var emailAttr = new Array("to","from","subject");
This creates a new array with the values:
0: "to"
1: "from"
2: "subject"
Then
var emails = new Array(emailAttr);
This creates a new array consisting of one value:
0: The array you created in the previous line
Then this:
emails[0].to = "abc1";
adds a new property to the first array:
0: "to"
1: "from"
2: "subject"
to: "abc1"
and then this:
emails[1].to = "abc2";
… tries to do the same to the second item in the emails array, but you haven't assigned an array there so you are trying to set a property on the undefined object which isn't allowed and you get an error.
You probably want to create an array (for your ordered list of email objects) of objects (not arrays, use objects for named values, use arrays for numerically indexed, ordered values), and you need to create a new object for each member.
var emails = [];
emails.push({
to: "abc1",
from: "...",
subject: "..."
});
You can then repeat that to add any many items as you like.
You can edit items in it (but only ones you have already created) using your original syntax:
emails[0].to = "abc1";
NB: Best practise is to use the [] and {} literals to create new arrays and objects, not the constructor functions Array() and Object().

You should make the email an object and push those into an emails array:
// Create emails array
var emails = [];
// Create an email object
var emailObj = {
to: 'mail#mail.com',
from: 'anothermail#mail.com',
subject: 'Hello there'
};
// Add the email to the emails array
emails.push(emailObj);
// Will console log "Hello there"
console.log(emails[0].subject);

You first have to define what the child object is. When you write emails[1].to, you're already trying to access that sub object before it's been defined.
Change it to:
emails = []; // create the main array
emails[0] = {to: 'abc1'}; // define an object and assign it to the main array
emails[1] = {to: 'abc2'};

You have to create an array which consists of objects.
So instead of these lines
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2";
you can simply write this:
var emails = [{
to: "abc1"
}, {
to: "abc2"
}];

Related

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 :(
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
};
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!');
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.
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 :)

Create Javascript object with one array property

How to create a javascript object runtime like following
task{
timestamp:string;
tasklist: array of object
}
You can use an object initialiser for that:
var task = {
timestamp: "this is a string",
tasklist: []
};
[] creates an array (an empty one). JavaScript doesn't have "array(s) of object," a standard array can hold anything. (JavaScript does, these days, have typed arrays for other things, like 8-bit integers, but not objects.)
var task = {
timestamp: new Date().getTime(),
tasklist: [new Object(), new Object()]
};
This could be one way to do it. Then you can get access to the property in this way:
task.tasklist[i...n]
You could also create an array like this:
var task = []
and then assign the timestamp as a property:
task.timestamp = //myTimestamp
var task = {};
task.timestamp = 'your string';
task.tasklist = [];
and then add task list objects like:
task.tasklist.push({'id': 5, 'name': 'task list 5'});
or:
var tasklistentry = {};
tasklistentry.id = 5;
tasklistentry.name = 'task list 5';
task.tasklist.push(tasklistentry);

jquery array with attribute

I want to create an array like this in JQuery:
id=1, name="pepe"
How can I do this? I have done this but not working
arr[idx]["id"].push( $(id).text());
arr[idx]["name"].push( $(name).text());
to later access to the id of the array like this:
(arr[0].id)
If your goal is to have an array where each entry in the array has id and name attributes, here's how:
Declare a variable:
var arr;
Create the array:
arr = [];
Add an entry to it which is an object with those properties:
arr.push({
id: $(id).text(), // I assume the `id` in `$(id)` is just placeholder for something
name: $(name).text() // Similarly the `name` in `$(name)`
});
In the above, provided $(id).text() returns "1" and $(name).text() returns "Pepe", you'll end up with an array with one entry, where that one entry is an object with id=1 and name=Pepe.
Then you can access (say) the first of those:
console.log(arr[0].id); // Shows the `id` property of the first object in the array
arr.push({id:1, name:"pepe"});
arr[idx].id = $(id).text();
arr[idx].name = $(name).text();

Count and record partially repeating objects in objects in a new Array Javascript

I need to work through a source array of objects, many of the objects in the array have three property values which will be the same. It is these values that will be used to create a new object and push it on to destination array. When another object on the source array comes up with the same three property values as one of the objects on the destination array the matching object on the destination array will have its visit count incremented by one.
To help you understand, in the source array each object is a record of a meal that belongs to a user. In the second array I need to store the user details and the number of their meals.
I've tried a few solutions which have failed like the one below. I thought that the code below would create a literal object, check if it is in the destination array by finding it's indexOf (-1 for not found) and if it's not found push it on. The problem is that it never finds the objects, if I search through 3000 meals the second array ends up 3000 long!
The code below does not try to store the visit count.
userArray = new Array();
for (var i = 0; i < filteredObjects.length; i++) {
var user = {
forname: filteredObjects[i].forname,
surname: filteredObjects[i].surname,
dincat: filteredObjects[i].dincat,
};
var index = userArray.indexOf(user);
if (index = -1) {
userArray.push(user);
}
}
This doesn't work because the user object that you create in the loop is not the same as any of the objects you added inside userArray. They might contain the same keys and values, but strictly speaking (===) they're not the same.
To help your code, you can add a user map object:
var userArray = new Array(),
userMap = {};
for (var i = 0, item; item = filteredObjects[i]; ++i) {
var userKey = item.forname + '-' + item.surname + '-' + item.dincat;
if (!(userKey in userMap)) {
userArray.push({
forname: filteredObjects[i].forname,
surname: filteredObjects[i].surname,
dincat: filteredObjects[i].dincat,
});
userMap[userKey] = true;
}
}
The user map is an object that uses its keys to determine whether you have already inserted a user before. This works by choosing a user identifier, in your case the combination of first name, surname and dincat.
indexOf compares search element to elements of the Array using strict equality. If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object. In your case, you create a new object every time and compare it with the existing objects in the array and it will return false.
There's several syntax errors there, but the major reason that code's not working is that what you're doing is creating a new object with the value of the object you currently at in the array loop, then looking for that new object in the array, so it's never going to be there.
I'm actually a little curious myself if there's a more efficient solution, but one possibility is
var demo = [
{a: 'green', b: 'blue', c:'red'},
{a: 'blue', b: 'green', c: 'not blue'},
{a: 'green', b: 'blue', c: 'red'}
],
records= {};
for (var i=0; i<demo.length; i++){
if (records.hasOwnProperty(demo[i].a) &&
records[demo[i].a].hasOwnProperty(demo[i].b) &&
records[demo[i].a][demo[i].b].hasOwnProperty(demo[i].c)
){
//do something with a match
} else {
if (!records.hasOwnProperty(demo[i].a))
records[demo[i].a] = {};
if (!records[demo[i].a].hasOwnProperty(demo[i].b))
records[demo[i].a][demo[i].b] = {};
records[demo[i].a][demo[i].b][demo[i].c] = 'yes';
//no match found
}
}
Just substitute your values in for a, b, and c and it should work.

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Categories

Resources