How to create object inside object in Javascript - javascript

I am trying to create an object - that each parameter inside it is another object:
var divTextPerScreenWidthMap = new Object(
{'360','click'},
{'480','click it'},
{'768','click it right'},
{'1024','you know you want to click it'},
{'1280','click this button which is very long will help you'}
);
This is not working since I am getting an error. how do I need to write it to make it work? Should I change the outer object into an Array and how?

You have syntactical errors.
First of all object literal follows the syntax below:
var literal = {
"Name": "value",
"Array": [],
"NestedObject": {}
};
Name value separator is the colon, not comma.
EDIT
The above code might be rewritten as follows
// declaration via array initializer
var myArray = [
// name : value syntax
{'360': 'click'},
// values separated by comma
{'480': 'click it'},
{'768': 'click it right'},
{'1024': 'you know you want to click it'},
{'1280': 'click this button which is very long will help you'}
]
however at this point you cannot access your objects via i'ts names like this:
var firstObject = myArray[0];
// will throw an error
firstObject.360 = "not click";
You can only use it as follows
firstObject["360"] = "not click";
Hence I suggest you to name the properties according to variable naming rules.

In javascript object is a simple map. It is better to use literal {} instead od new Object();
var myObj = {
prop : {},
prop2 : {}
}

Don't create an Object via its constructor, use the literal syntax {}.
Also, objects have keys and properties. Your objects seem to only have values. Did you mean to use Arrays?

You completely forgot to give keys for your values. If you don't want to use keys, use arrays:
var divFoo = [
[360, "click"],
[480, "click it"] // et cetera
];
This would give you an array of arrays. For instance, divFoo[0][0] == 360
If you want keys, use an object:
var divFoo = {
"360": "click",
"480": "click" // et cetera
}
This gives you simple object. divFoo[360] == "click"
Or you could use an array of objects for more descriptiveness:
var divFoo = [
{time: 360, text: "click"},
{time: 480, text: "click it"} // et cetera
];
In this case, divFoo[1].text == "click it".
Also, a few hints:
Don't use new Object or new Array. They're redundant.
There's no need to quote integers if they're used as values.

It would make sense to represent your collection of objects as an array:
var divTextPerScreenWidthMap = [
{360:'click'},
{480:'click it'},
{768:'click it right'},
{1024:'you know you want to click it'},
{1280:'click this button which is very long will help you'}
];
//You could iterate over your array of objects with a for loop:
var i, value;
for (i=0; i < divTextPerScreenWidthMap.length; i++) {
value = divTextPerScreenWidthMap[i];
console.log(value);
};
//Alternatively, you could represent your data structure as one object:
var divTextPerScreenWidthMap = {
360:'click',
480:'click it',
768:'click it right',
1024:'you know you want to click it',
1280:'click this button which is very long will help you'
};
//So now if you have a screen width, you can quickly get back the corresponding message:
var screenWdith = 360;
alert(divTextPerScreenWidthMap[screenWidth]);

You can also created nested objects like this:
let obj1 = {};
obj1['title'] = 'Vehicles';
let obj2 = {};
obj2['name'] = 'Honda City';
obj1['cars'] = obj2;
console.log(obj1);

Create a method in object, create a new object in that method and return it.
const obj = {
one: "one is just a property",
two: function(){
const newObject = {
three: "now two will return new a new object"
}
return two;
}
}

Related

push Object in array in $.each

Maybe I'm just blind, but I'm struggling for a good amount of time now:
I have a small piece of JS-Code here:
var linkInput = $('#Link input.gwt-TextBox').val();
var parentRow = $('#Link').parent().parent();
var links = linkInput.split("|");
// hide text-input
$(parentRow).hide();
// get rid of empty elements
links = links.filter(Boolean);
var aSites = [];
var oSite = {};
$(links).each(function (k, v) {
splits = v.split(".");
domainName = splits[1];
oSite.name = domainName;
oSite.url = v;
aSites.push(oSite);
});
console.log(aSites);
To specify: Get the value of an input-field, hide the row afterwards and save all the values in an object, which is then pushed into an array.
The parameter, taken from the console-tab of google Chrome:
var links = ["www.myshop1.de/article/1021581", "https://www.myshop2.de/article/1021581"] [type: object]
I thought, I iterate through all elements of this object (in that case 2 times), push the values into an object and the object into an array, to have access to all of them afterwards.
At some point however, I seem to override my former values, since my output looks like this:
0: {name: "myshop1", url: "https://www.myshop1.de/1021581"}
1: {name: "myshop2", url: "https://www.myshop2.de/1021581"}
length: 2
__proto__: Array(0)
Where is my mistake here? Is there a smarter way to realize this?
On a sidenote:
I tried to use only an array (without adding an object), but it seems like I
can't use an associative key like this:
var myKey = "foo";
var myValue = "bar";
myArray[myKey] = myValue
You should move this:
var oSite = {};
...inside the each callback below it, because you need a new object in each iteration.
Otherwise you are mutating the same object again and again, pushing the same object repeatedly to the aSites array, which ends up with multiple references to the same object.
Not related, but you can use $.map to create your array (or vanilla JS links.map()):
var aSites = $.map(links, function(v) {
return { name: v.split(".")[1], url: v };
});

How to create object of array in Javascript

I want to create the object of list that looks like this:
myObj = {"foo":[1,2,3,4],
"bar":[3,5,7,8]}
I tried this but failed
var myObj = new Object();
myObj["foo"].push(1)
myObj["foo"].push(2)
#...etc
What's the right way to do it?
You need to create the array first
myObj["foo"] = []
then call your push method
It depends, are you trying to reassign the myObj attribute foo with a completely new array? Or are you trying to append to the already existing array?
In the former case:
myObj.foo = [1,5,6,4] // new array
And in the latter:
myObj.foo.concat(/*new numbers*/)
The {} notation is commonly used.
var myObj = {};
myObj.foo = [];
myObj.bar = [];
Later you can manipulate the arrays.
myObj.bar.push('elem1');
myObj.bar.pop();
// ...
First you should declare the properties of the object as array in order not to get some unpleasent situations.So you can use new Object to create an object like this.
var myObj=new Object;
and define properties as empty arrays
myobj.prop1=[];
myObj.prop2=[];
then you can push whatever you want into prop1 or prop2 by simply reaching them inside the object as
myObj.prop1.push(someData)
OR
You can use a better way to declare this object like below
var myObj={
prop1:[],
prop2:[]
}
And again you can push whatever you like into them as i told above
as myObj.prop1.push(data)
Try first declare your object, so your second line goes first
var myObj = new Object();
then you fill your object with data
myObj = {"foo":[1,2,3,4],"bar":[3,5,7,8]}
then the rest of your code should work fine
myObj["foo"].push(1)
myObj["foo"].push(2)
result [ 1, 2, 3, 4, 1, 2 ]

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

How to add an element containing fields to an array

Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:
shopsArray[4].shopName
Edit:
It's working with Pointy's answer but I still have a problem:
shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );
The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.
Can you see what's the problem here?
Edit 2:
More elaborate code:
// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();
// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
shopsArray[i].shopName = $('#secondaryName' + i).val();
shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}
// save new branches to array
for (var j=1; j<=newshopsCounter; j++){
var bName = $('#newName' + j).val();
shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});
alert(bName);
alert(shopArray[1].shopName);
alert(shopsArray[1].shopId);
}
The first and third alerts give the correct values. The second one gives undefined.
You mean something like
shopsArray.push({ shopName: "Fred", value: "Ethel" });
?
edit — now that I know that this is the sort of thing you want to do, I'll clarify.
JavaScript has an "object literal" syntax that allows objects to be created directly as values. The syntax involves a list of property names and values, with the names and values separated by a colon and each pair separated by commas. Thus:
var anObject = { someProperty: "the value" };
creates an object with one property and assigns it to the variable "anObject". That's effectively the same as:
var temp = new Object();
temp["someProperty"] = "the value";
var anObject = temp;
The "value" part of a property in an object literal can be any expression, but the property name must be either a string constant or an identifier (and in either case, it's treated like a string constant). Thus, you can create an object with a property whose value comes from calling some function:
var fancyObject = { "temperature": getTemperature() };
Object literal expressions are values, and can be used anywhere you can use an expression, including function call arguments. Therefore, to add an object to an array, it's possible to call the array ".push()" function and use an object literal as the argument, as in the first example:
shopsArray.push({ shopName: "Cheese Shoppe", shopPhone: "111 222 3232" });
You can even include object literals inside another object literal, as the value of a property:
shopsArray.push({
shopName: "Cheese Shoppe",
shopAddress: {
street1: "207 High Street",
street2: "No. 5",
city: "Austin",
state: "TX"
}
});
You would simply create a hash inside an array to achieve that:
var shopsArray = [
{
shopName: 'value1'
}, {
shopName: 'value2'
}
];
If you have an existing array, use push:
shopsArray.push({ shopName: 'value' });
you can do something like this:
var arr = new Array();
arr['field_name'] = 'field_value';
//to access it on ajax
for (var i in arr){
//field_name is in "i"
//field_value is in arr[i]
}

What does [] mean in JavaScript?

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?
var openTollDebug = [];
it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate
// let's overwrite the Array object
Array = function(id) {
this.id = id;
}
var a = new Array(1);
var b = [];
console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false
console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b
b.push(2);
console.log(b); // outputs [2]
It means an array.
var openTollDebug = [];
declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:
var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
It's an empty array, and is equal to
var openTollDebug = new Array();
It is shorthand for empty array. Same as new Array().
Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.
It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:
openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};
As an array, you can add items:
openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Many languages have constructs for literals. The [] is an Array literal.
var openTollDebug = [];
is the same as
var openTollDebug = new Array();
Just know that using [] preferred for performance reasons.
There are other literals like Object literals
var MyObject = {
name:'default',
age:22,
hobbies:["golf","video games","otherstuff"]
}
Notice the array literal with data. The [] creates an empty array.
Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it
var b = [] //it is an array literal.

Categories