I have a problem with creating list with objects in JavaScript: the object is going to contain an Integer value and an array.
The structure will look like this (this code works):
var list = [ {
id : 1234,
dependencyList : [ {
id : 2142
}, {
id : 5313
} ]
}, {
id : 4312,
dependencyList : [ {
id : 2142
}, {
id : 5313
} ]
} ];
The problem is that I want to create this list dynamically, in other words something like this:
var list = [];
var object;
object.id=1234;
object.dependencyList = [];
object.dependencyList.push(2222);
list.push(object);
This code does not work when I try to alert(list[0].length) and it returns 0 and after using JSON.stringify(list) it only returns [[]].
Anyone know a solution for this?
4 Answers 4
list[0] is an object and not an array, which is why you're not seeing anything for length. Try:
console.log(Object.keys(list[0]).length);
Or you could even just console.log(list[0]) and check your console to ensure that it contains something.
Also, I assume you meant:
var object = {};
Because otherwise object is undefined and your script won't work. Another thing you will have to change is:
object.dependencyList.push(2222);
to:
object.dependencyList.push({id: 2222});
3 Comments
Object isn't defined. Do:
var object = {};
1 Comment
You should do list[0].dependencyList.length) also you shoud change:
object.dependencyList.push(2222);
for
object.dependencyList.push({id: 2222});
Comments
Objects are your friend.
If you need to create a lot of these things, you should probably define how they are shaped in a function. An advantage of this is that you can then create a setter for adding a dependency that hides the implementation as a push against a particular member variable.
Something like this:
function createObject( id ) {
var object = {};
object.id = id;
return object;
}
function createObjectWithDependencies( id ) {
var object = createObject( id );
object.dependencyList = [];
object.addDependency = function( dependentObject ) {
object.dependencyList.push( dependentObject );
}
return object;
}
var list = [];
var object = createObjectWithDependencies( 1234 );
object.addDependency( createObject( 2142 ) );
object.addDependency( createObject( 5313 ) );
list.push( object );
var object = createObjectWithDependencies( 4312 );
object.addDependency( createObject( 2142 ) );
object.addDependency( createObject( 5313 ) );
list.push( object );
console.log( list );
list[0] == { id : 1234, dependencyList : [ { id : 2142 }, { id : 5313 } ] }var object = {};???list = { 1234 : [ 2142, 5313], 4312 : [2142, 5313] };