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);
Related
I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);
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 :)
I have a multi dimensional array like this:
var firstElement = $(this).first();
fielddata = {
number: index,
attributes: [
{ 'label_text': firstElement.text(),
'label_width': firstElement.width(),
'label_height': firstElement.height(),
'label_color': firstElement.css('color')
}
]
}
How can I change one of the values inside the attributes part but by id? so I make 'label_text' a different value?
I do not want to use the index.
You don't have a multidimensional array. You have an object; one of its properties is an array of objects.
In this case, it looks like you want to update label_text in the first (and only) object in the attributes list. If that's correct:
fielddata.attributes[0].label_text = 'whatever';
Will work, as would:
fielddata.attributes[0]['label_text'] = 'whatever';
I am currently working on a website type project and I am new to JavaScript. So I have been having troubles with some parts of the syntax. Basically I am trying to print the 'id' and 'value' in the nested array arr.
var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})};
var obj = myArray[0];
document.write(obj.id);
this will print the id 1 but im not sure how to access id 10.
Also if there is an easier way to do this let me know please!
Firstly, don't use the new Array constructor. Just define an array literal [...]. So your myArray will look like:
var myArray = [{id:'1', value:'een', arr: [{id:'10', value:'een'}]}];
To get to the id of 10, you need to access myArray[0].arr[0].id;.
Proper reference would be:
obj.arr[0].id
PS: google chrome developer console is a goot playground for testing javascript object dereefrecing
You can't without iterating over the array.
If order does not matter, use an object instead:
var myObject = {
1: {id:'1', value:'een'},
10: {id:'10', value:'een'}
};
var obj = myArray[10];
document.write(obj.id);
In case the nesting in your array is intended, here's what you want:
var obj = myArray[0].arr[0];
Demo:
> var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})});
> myArray[0].arr[0]
{ id: '10', value: 'een' }
I would for get arrays why not create your own object ?
http://www.w3schools.com/js/js_objects.asp
I have a javascript object that contains a few objects that contain associative arrays. I've been trying to use the json2.js library's stringify function but the output doesn't contain the arrays held in the contained object members.
In my code I start with something like this
obj = {"arr1" : [], "arr2" : [], "arr3" : []};
then I add to it with loops that fill each of the contained arrays
obj[arr*].push[arritem*];
obj[arr*][arritem*] = something;
The arr* and arritem* I put in just to represent the variable I am putting in for the loops.
I try Json.stringify(obj) but the string I get back is
'{"arr1" : [0], "arr2" : [0], "arr3" : [0]}'
I would like to see the ouput as
'{"arr1" : [ "arritem1" : something, "arritem2" : something2], "arr2" : [ "arritem1" : something, "arritem2" : something2], "arr3" : [ "arritem1" : something, "arritem2" : something2]}'
is there a better library for this or is there something I have to do before strinfying?
var obj = {"arr1" : [], "arr2" : [], "arr3" : []};
console.log(JSON.stringify(obj));
Works for me.
Filling the arrays works too.
Update
You imply that you are trying to add elements with non-numeric keys to arrays.
This is not valid. In particular, your desired output is not valid JSON. Arrays have only numeric keys, and they are not included in the JSON itself as they are implicitly, sequentially defined.
Arrays are a special type of Object, which handles numeric indexes for you.
var arr = []; // Create array.
arr.push(1); // There is now one element, with index 0 and value 1.
arr["txt"] = 2; // You tried to create a new element,
// but didn't use .push and gave a non-numeric key.
// This broke your array.
console.log(JSON.stringify(arr));
// Output: [1]
Live demo.
Long story short... don't do this. If you want an "associative array", stick with basic objects:
var obj = {}; // Create object.
obj[0] = 1; // There is now one element, with key "0" and value 1.
obj["txt"] = 2; // There is now a second element, with key "txt" and value 2.
console.log(JSON.stringify(arr));
// Output: {"0":1,"txt":2}
Live demo.
obj.toSource()
this will convert your array to source string.