How to put object inside another object using javascript - javascript

var noOfChild=document.getElementById('btnInput').value;
for(var i=1;i<=noOfChild;i++){
createJSON();
function createJSON() {
alert('working')
var jsonObj =[];
var startId=1;
$("span[id=childNo]").each(function() {
var idChildName='childName'+startId;
var childName=document.getElementById(idChildName).value;
var idDobChild='dobChild'+startId;
var dobChild=document.getElementById(idDobChild).value;
var idSchoolName='schoolName'+startId;
var schoolName=document.getElementById(idSchoolName).value;
var idClassSection='classSection'+startId;
var classSection=document.getElementById(idClassSection).value;
alert(childName);
var item = {};
item ["child_name"] = childName;
item ["child_DOB"] = dobChild;
item ["child_class"] = classSection;
item ["child_school_name"] = "KV_32";
// jsonObj.push("{'"+startId+"':['"+item+"']}");
jsonObj.push(item);
startId=startId+1;
});
var obj={
"1":jsonObj
};
console.log(obj);
I want object like this:
{"1":{"child_name": "ytfy", "child_DOB": "1993-06-18", "child_class": "d", "child_school_name": "KV_32"}}
But i am getting like this:
1:{child_name: "ytfy", child_DOB: "1993-06-18", child_class: "d", child_school_name: "KV_32"}

This implementation in my opinion is a lot cleaner and nicer to see. The only thing you have to understand is that by calling objectResult["1"] you also create a field "1"
var object = {"childName":"foo", "childSurname":"foo"};
var objectResult = {}
objectResult["1"] = object;
console.log(objectResult);

It looks like you might be simply misreading console.log()
If you try this code:
var obj = {
'1': {
test: 'some data'
}
}
console.log(obj)
It outputs 1: {test: "some data"} to the chrome dev tools console, however it sits below an expandable line that says Object, indicating that the line is in fact a child key of an object. So while the console shows this, the actual object does in fact look like:
{
'1': {
test: 'some data'
}
}

var foo = { "oh" : "yeah" };
var bar = { "no" : "way" };
bar["foo"] = foo;
console.log(bar);

Related

Can we use concatenated values and variables for Object Keys?

I have a object
let x = { "propName": "response" }
Is there a way we can change the key name for the object. I would like to pass an index for the propName like
{ "prop1Name": "response" }
Is there a way to do this, I know I cant do it like this but, I tried it with
var obj = { "prop"+i+"Name": "response" };
console.log(obj);
But, it failed ofcourse.
Is there a way to do it?
You can use the new ES6/Babel syntax of {[keyfromvariable]:"value"}, so, in your case...
var i = "1";
var obj = { ["prop"+i+"Name"]: "response" };
console.log(obj);
If you don't have ES6/Babel as an option, you can define the object first and then use []...
var i = "1";
var obj = {};
obj ["prop"+i+"Name"] = "response" ;
console.log(obj);

Javascript - get object value using variable

I'm trying to get an object value by passing a variable to a function, but I'm not sure how to do this with a multi layer object. It looks like this:
var obj = {
field1: { name: "first" },
field2: { name: "second" }
};
var test = function(field){
//sorting function using obj[field]
//return results
};
With the above, the following works:
var result = test("field1");
This sorts using the object {name: "first"} but say I want to use just the name value. I can't do this:
var result = test("field1.name");
What is the correct way to do this?
what about this?
var result = test("field1", "name");
var test = function(field, keyname){
return obj[field][keyname];
};

Concatenate object field with variable in javascript

I'm building an object in javascript to store data dynamically.
Here is my code :
var id=0;
function(pName, pPrice) {
var name = pName;
var price = pPrice;
var myObj = {
id:{
'name':name,
'price':price
},
};
(id++); //
console.log(myObj.id.name); // Acessing specific data
}
I want my id field to be defined by the id variable value so it would create a new field each time my function is called. But I don't find any solution to concatenate both.
Thanks
You can create and access dynamicly named fields using the square bracket syntax:
var myObj = {};
myObj['id_'+id] = {
'name':name,
'price':price
}
Is this what you want ?
var myObj = {};
myObj[id] = {
'name':name,
'price':price
};
console.log(myObj[id]name); // Acessing specific data
You can use [] to define the dynamic property for particular object(myObj), something like
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
Example
function userDetail(id, nom, prix) {
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
return myObj;
}
var objA = userDetail('id1', 'sam', 2000);
var objB = userDetail('id2', 'ram', 12000);
var objC = userDetail('id3', 'honk', 22000);
console.log(objA.id1.nom); // prints sam
console.log(objB.id2.nom); // prints ram
console.log(objC.id3.prix);// prints 22000
[DEMO]

Is it possible to refer to a "real-time parent" function's variable from inside of a function of the same array?

I fully realize that this code is kinda strange by the very nature of javascript, but look at it:
var arr = [
function () {
this.b = "hello";
//or var b = "hello";
arr[1]();
},
function () {
var str = RealtimeParentFunc.b;
alert(str);
// want to get "hello"
}
];
// want to get "hello"!
arr[0]();
Maybe it's impossible, but I wonder if there's a way of doing this. How to get a variable of an array's function that called a function in the same array?
UPDATE
I had to go back to this problem and decided to post an update: of course I can't reference arr[i] from within itself, but I must emphasize that the code above was not supposed to be taken too literally: it was just a demo of what I wanted; but it looks like I can do what I want if I have a small "adjuvant" function that is previously defined in the code:
var a = function (i, v) {
return arr[i]()[v];
};
var arr = [
function () {
var h = "hello, ";
var n = a(2, "n");
return {
"h": h+n
}
}, function () {
var h = a(0, "h");
alert(h)
}, function () {
return {
"n": "your name"
}
}];
arr[1]();
You can't define an array and access it's values at the same time, since at the time of creation, the arr2 does not exist yet.
The [ function(){ .. }, function(){ .. }] array isn't created and set to arr2 until it reaches the ; semicolon at the end. Therefore you can't reference arr2[1]() while it's being defined.
On that note, what you can do is define the array first, then .push() the functions into it, but you're still limited to doing it sequentially:
var arr2 = [];
arr2.push(
function () {
var b = "hello";
//arr2[1](); // CAN'T DO THIS since arr2[1] doesn't exist
return {
b: b
};
});
arr2.push(
function () {
var str = arr2[0]().b;
alert(str);
// want to get "hello"
});
// want to get "hello"!
arr2[0]();
arr2[1]();
See working fiddle: http://jsfiddle.net/amyamy86/5k57X/

Nested objects in javascript, best practices

I would like to know the correct way to create a nested object in javascript. I want a base object called "defaultsettings". It should have 2 properties (object type): ajaxsettings and uisettings. I know that i can write something like
var defaultsettings = new Object();
var ajaxsettings = new Object();
defaultsettings.ajaxsettings = ajaxsettings.. etc.
But what i want to know is how to type it this way (that i suppose is a more correct way of doing it):
var defaultsettings = {
var ajaxsettings = { ... }
};
I suppose you get the idea. Thanks!
If you know the settings in advance you can define it in a single statement:
var defaultsettings = {
ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
};
If you don't know the values in advance you can just define the top level object and then add properties:
var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:
var defaultsettings = {
ajaxsettings : { },
uisettings : { }
};
defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";
You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:
var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";
Note that you can not use variables for key names in the { } literal syntax.
var defaultsettings = {
ajaxsettings: {
...
},
uisettings: {
...
}
};
var defaultSettings = {
ajaxsettings: {},
uisettings: {}
};
Take a look at this site: http://www.json.org/
Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.

Categories

Resources