I tried a lot searching and didnt get desired solutions.
What I want to achieve is
var myObject {
id1 : {
name:place_name,
location : place_loc
},
id2 : {
name:place_name,
location : place_loc
},
id3 : {
name:place_name,
location : place_loc
}
}
What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.
I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.
My code looks something like this.
var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";
But it gives error.
I know it seems simple doubt but any help would be grateful.
Thanks in advance. :)
You are trying to set a value of already assigned objects at keys "idnumber1", etc.
What you'll need is to initialize each objects for your ids like this:
var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.
function Place(name, location) {
this.name = name;
this.location = location;
}
var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);
To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).
An example:
var myObject = {};
for (i = 0; i < 20; i++){
myObject["id" + i] = {name: place_name, location: place_loc}
}
In practice, you can use a counter that you increment outside of a loop.
Related
How would I add a "property" to an object? I tried: players[data.id].name = data.name;
but it's not working.
Edit: this worked, thanks for the help guys!:
players[data.id] = {name: "Johnny"};
What I want to achieve: (data.id is already defined)
var players = {};
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id].name]); ---> Johnny
welcome to stackoverflow ! You need to define what players[data.id] is first.
Then you can assign data to it. In your example, you are only logging the name property of your object, remove the .name to show the whole object.
let data = { id: "test" };
var players = {};
players[data.id] = {}
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id]);
First, you have to declare 'players[data.id]' as an object.
The flow of the code would be like
var players = {};
players["dataId"] = {};
players["dataId"].name = "Johnny";
players["dataId"].age = 13;
console.log(players["dataId"].name);
This is what i have so far. Basically every time i make a new Item object i need it to create a specific number of another object called Sensor. I've tried a few other methods and none seem to way the work that i need.
function Item (id,number,operator,numOfSensors){
this.id = id;
this.number = number;
this.operator = operator;
this.numOfSensors = numOfSensors;
var sensor = new Sensor[numOfSensors];
}
var Sensor = {
timeStamp:[],
itemPassed: function(){
timeStamp.push(Date.now());
}
}
Thanks so much for any help :) i'm a bit new to js
EDIT:
Hey guys! Thanks for the help. Basically my issue is neatly making an array of Objects. In the item object i want to make a [numOfSensors] amount of the Sensor object. I cant seem to find a way to do that. SO i guess my question is how would i go about creating an array of objects with a set number of elements?
Not sure when you really want to call itemPassed() and whether this is not rather a function of Item, but here is some code that might get you get started:
var Item = function (id, number, operator, numOfSensors) {
this.id = id;
this.number = number;
this.operator = operator;
this.numOfSensors = numOfSensors;
var sensorArray = [];
for (var i = 0; i<numOfSensors; i++) {
sensorArray.push(new Sensor());
}
}
var Sensor = function() {
this.timeStamps = [];
}
Sensor.prototype.itemPassed = function(){
this.timeStamps.push(Date.now());
}
See:
How to initialize an array's length in javascript?
http://code.tutsplus.com/tutorials/prototypes-in-javascript-what-you-need-to-know--net-24949
I'm trying to create an object where there is a key value pair, and the value is an array.
i.e:
foo = {'key1':['val1','val2'], 'key2':['v3','v4']};
Is this possible in pure JS?
e.g.
var foo = {};
foo['key1'] = ['keyOneVal1'];
foo['key1'] = ['keyOneVal2'];
but as you may have guessed, this just overwrites the keyOneVal1.
I've also tried
var foo = {};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
but couldn't get it working in a jsfiddle.
EDIT:
Okay heard you guys loud and clear.
This object will not be initialized with an starting key, it's dynamically inserted based on time. So in the end the object will look more like
foo = {'time1':['a','b'], 'time2':['c','d','e','f'], 'time3':['y','y']};
It's very possible. Your second example is the correct way to do it. You're just missing the initializer:
var foo = {};
foo['key1'] = [];
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
for(var i = 0; i < foo['key1'].length; i++) {
document.write(foo['key1'][i] + '<br />');
}
Try something like this make sure you declare key1:
var foo = {"key1" : []};
foo['key1'].push('k1v1');
foo['key1'].push('k1v2');
It can be done like this
var foo = {"key":[]}
foo["key"].push("val1")
foo["key"].push("val2")
It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}
I have an object within an object. It looks like this.
var myLib = {
object1: {}
}
My basic problem is that I wanted to end up like this. So I would like to do this dynamically I will not know the property's or additional objects until run time.
var myLib = {
object1: ({"A1":({"Color":"Blue",
"height":50})
})
}
From reading here on Stack Overflow I know that I can create an object within an object by simply going like this:
myLib.Object1["A1"] = "Something"
But this does not produce what I'm looking for.
I tried this syntax which I know is wrong but basically
mylib.Object1["A1"].["color"]="Blue";
so basically here is the question. I would like to create object "A1" under "mylib.Object" and immediately add property color = "blue" to "A1". I would need to do this for several other properties, but if I can figure out how to do this for one, I can figure it out for the rest. How can I accomplish this task?
No jQuery, please. Just plain old JavaScript is what I'm looking for.**
Once I create the object and properties I would imagine I can just use a for loop to loop through the properties for that object. Like so:
for(key in mylib.Object1["A1"]){}
Right?
You can create it all from scratch like this:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
myLib.object1[x] = {Color: "Blue", height: 50};
Or, if all values are in variables:
var myLib = {};
myLib.object1 = {};
// assuming you get this value from your code somewhere
var x = "A1";
var colorProp = "Color";
var colorPropValue = "Blue";
var heightProp = "height";
var heightPropValue = 50;
myLib.object1[x] = {}; // create empty object so we can then add properties to it
myLib.object1[x][colorProp] = colorPropValue; // add one property
myLib.object1[x][heightProp] = heightPropValue; // add another property
These syntaxes create identical results:
myLib.object1.A1 = {};
var x = "A1";
myLib.object1[x] = {};
The first can only be used when the property name is known when you write the code and when the property name follows the proper rules for a javascript identifier. The second can be used any time, but is typically used when the property name is in a variable or when it doesn't follow the rules for a javascript identifier (like it starts with a digit).