JavaScript Custom JSON Names Childs - javascript

I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
works. But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
I tried some things but its not working :(
I need to create the JSON like this because I needs variables as parents

I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
That's not a JSON array, that's a JavaScript object.
But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
That's because you're setting a property on a string primative. That will temporarily promote the string primative to an object, set the property, and then throw away the object, effectively doing nothing.
To make someJSON.number an object, create an object just like you did for someJSON and add properties to it. Or you can do it all at once:
let obj = {
number1: {
date: "19.01.2017"
}
};
If you want "someString" in there somewhere, just put it on another property:
let obj = {
number1: {
str: "someString",
date: "19.01.2017"
}
};

You have to create the "number1" object first. Note that you won't be able to set a string value for "number1" as it is now an object.
let someJSON = {};
someJSON["number1"] = {};
someJSON["number1"]["date"] = "19.01.2017";

Related

Object keys - Javascript: why doesn't work to create object inside object?

I don't know if I am mind-collapsed or just need to work harder with objects, but I don't get why this doesn't work:
const obj = {};
const obj['pagination']['searchword'] = searchWord;
It says:
Cannot set property 'searchWord' of undefined
It looks like I can't create that kink of object:
console.log(obj)
{
pagination:{searchWord:valueOfSearchWordVariable}
}
I tried to with const obj.pagination['searchword'] = searchWord;
If you want to create an object inside an object, you have to define the object explicitly somewhere. If you try to access a property of an object as if it was a nested object, one won't automatically be created.
For your case, it would be easier to define the object all at once, in one statement, not two:
const obj = {
pagination: {
searchword: searchWord
}
};
If you have to assign after object initialization, then you'd do:
obj.pagination = {
searchword: searchWord
};
If you change the searchWord variable name so it matches the lower-case property name, you can use shorthand notation:
obj.pagination = {
searchword
};
You have to define obj['pagination'] first. Now you are assigning to an undefined.
obj is an empty object. But what is obj['pagination']? it is not set yet. And while obj['pagination'] is not set you are trying to assign a property to it.
you also can assign an empty object.
obj['pagination'] = {};
and then you can do this.
obj['pagination']['searchword'] = searchWord;
Another way to do this
Object.defineProperty(obj, 'pagination', {
searchword: searchWord
});

Is it necessary to create nested jSON objects before using it?

I think I've seen how to create a JSON object without first preparing it. This is how i prepare it:
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now I think I can insert a value like: obj.0.type = "type0"; But I'd like to create it while using it: obj['0']['type'] = "Type0";.
Is it possible, or do I need to prepare it? I'd like to create it "on the fly"!
EDIT
I'd like to create JS object "On the fly".
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now i think i can insert value like: obj.0.type = "type0";
I guess you mean "assign" a value, not "insert". Anyway, no, you can't, at least not this way, because obj.0 is invalid syntax.
But I'd like to create it while using it: obj['0']['type'] = "Type0";
That's fine. But you need to understand you are overwriting the existing value of obj[0][type], which is an empty object ({}), with the string Type0. To put it another way, there is no requirement to provide an initialized value for a property such as type in order to assign to it. So the following would have worked equally well:
obj = {
0:{},
1:{},
2:{}
};
Now let's consider your second case:
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
Think closely about what is happening. You are creating an empty obj. You can assign to any property on that object, without initializing that property. That is why the assignment to obj.test works. Then in your second assignment, you are attempting to set the test property of obj.test, which you just set to the string "test". Actually, this will work--because strings are objects that you can set properties on. But that's probably not what you want to do. You probably mean to say the previous, string value of obj.test is to be replaced by an object with its own property "test". To do that, you could either say
obj.test = { test: "test" };
Or
obj.test = {};
obj.test.test = "test";
You are creating a plain object in JavaScript and you need to define any internal attribute before using it.
So if you want to set to "Type0" an attribute type, inside an attribute 0 of an object obj, you cannot simply:
obj['0']['type'] = "Type0";
You get a "reference error". You need to initialize the object before using it:
var obj = {
0: {
type: ""
}
};
obj['0']['type'] = "Type0";
console.log(obj['0']['type']);
You could create your own function that takes key as string and value and creates and returns nested object. I used . as separator for object keys.
function create(key, value) {
var obj = {};
var ar = key.split('.');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] = {} : a[b] = value
}, obj)
return obj;
}
console.log(create('0.type', 'type0'))
console.log(create('lorem.ipsum.123', 'someValue'))
Is it necessary to create nested objects before using it?
Yes it is, at least the parent object must exist.
Example:
var object = {};
// need to assign object[0]['prop'] = 42;
create the first property with default
object[0] = object[0] || {};
then assign value
object[0]['prop'] = 42;
var object = {};
object[0] = object[0] || {};
object[0]['prop'] = 42;
console.log(object);
Create object with property names as array
function setValue(object, keys, value) {
var last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = {};
setValue(object, [0, 'prop'], 42);
console.log(object);

Getting a reference to an array element

While I realize that an array, as a non-primitive data type, is handled by references in JavaScript, not by value, any particular element of that array could be a primitive data type, and I assume then that it is not assigned by reference.
I'd like to know how to get a reference to an individual element in an array so that I don't have to keep referring to the array and the index number while changing that element?
i.e.
var myElement=someArray[4]
myElement=5
//now someArray[4]=5
Am I misinterpreting various docs that imply but do not explicitly state that this is not the intended behavior?
You can make a copy of an array element, but you can't create a value that serves as an alias for an array property reference. That's also true for object properties; of course, array element references are object property references.
The closest you could get would be to create an object with a setter that used code to update your array. That would look something like:
var someArray = [ ... whatever ... ];
var obj = {
set element5(value) {
someArray[5] = value;
}
};
Then:
obj.element5 = 20;
would update someArray[5]. That is clearly not really an improvement over someArray[5] = 20.
edit — Now, note that if your array element is an object, then making a copy of the element means making a copy of the reference to the object. Thus:
var someArray = [ { foo: "hello world" } ];
var ref = someArray[0];
Then:
ref.foo = "Goodbye, cruel world!";
will update the "foo" property of the object referenced by someArray[0].
You can always pass around a closure to update this:
var myUpdater = function(x) {
someArray[4] = x;
}
myUpdater(5);
If you want read/write capabilities, box it:
var makeBox = function(arr, n) {
return {
read: function() { return arr[n]; },
write: function(x) { arr[n] = x; }
};
}
// and then:
var ptr = makeBox(someArray, 4);
ptr.read(); // original
ptr.write(newValue);
someArray[4]; // newValue

create object within object Javascript

My Code :
for( var i in zones) {
var latlons1 = new google.maps.LatLng(zones[i].b.cen_x, zones[i].b.cen_y);
var latlons2 = new google.maps.LatLng(zones[i].b.max_x, zones[i].b.max_y);
var latlons3 = new google.maps.LatLng(zones[i].b.min_x, zones[i].b.min_y);
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} } //here object creation
console.log(obj1);
}
what i am doing wrong? consol log error shows at object create.
When creating an object literal in JavaScript the key and value are separated by a colon (:). Also note that if you want to use dynamic keys then you'll need to use the square bracket notation for setting and accessing those properties. So this:
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} }
should become:
obj1 = {};
obj1[zones[i].n] = {
1: latlons1,
2: latlons2,
3: latlons3
};
If you're confused as to why you have to do it this way it's because the keys aren't evaluated. While you meant that the key should be the value that's referenced by zones[i].n, JavaScript interprets it as the key should be the string literal "zones[i].n", which obviously isn't what you want.
To use an object within an object,
//An object within an object
var NestedObject=new Object();
NestedObject.one={
sad:{
d:"Add"
}
}
I solved this using experimental coding within Codecademy.com;
Thanks for letting me share my answer!

C structure to JSON

I am very new to JS, have been working in C/C++ before,
I need an equivalent of below C structure in JSON
struct tmp_t{
int a;
char c_str[1024];
};
struct tmp2_t{
int a2;
.
.
char c2_str[1024];
};
struct my {
int number;
struct tmp_t tmp[100];
struct tmp2_t tmp2[100][1000];
};
For a json like
var myJSON = {
"number":0,
.
.
};
I need to access it like
myJSON.tmp[0].a = 10;
myJSON.tmp2[0][1].c2_str = "hello world"
any input is highly appreciated
Javascript properties are not typed like they are in C so there is no purely "equivalent" expression in javascript. You don't predeclare typed data structures like your C code has. I given variable or property in javascript can be assigned any value or reference - there is not hard typing. So without variables that can only contain a specific type like C has, there's no pre-declaring of data structure definitions like you have included from C.
Instead, you just declare the properties you want to use on a live object or if you intend to use many of them, you can create a prototype which you can instantiate when needed.
A direct declaration of a live object instance somewhat like your last structure would look like this:
var my = {
number: 10,
tmp: new Array(100),
tmp2: new Array(100)
};
This would declare an object named my that had three properties called number, tmp and tmp2. number initially contained the number 10 and the other two properties contained arrays of length 100 who's values were undefined. I don't know of any compact way to predefine your two dimensional array in javascript without running code in a loop to initialize it.
This data defintion would let you access my.number, my.tmp and so on.
If you want your arrays to contains objects with properties themselves, then you need to populate those arrays with the objects.
var my = {
number: 10,
tmp: [{a: 1, c_str: "foo"}, {a: 2, c_str: "whatever"}],
tmp2: new Array(100)
};
Or, in code, you could add in item to the tmp array with code like this:
var my = {
number: 10,
tmp: [],
tmp2: []
};
my.tmp.push({a: 1, c_str: "foo"});
my.tmp.push({a: 2, c_str: "whatever"});
Or, you could create the object separately and then put it in the array:
var obj = {}; // new empty object
obj.a = 1; // assign property
obj.c_str = "foo"; // assign property
my.tmp.push(obj); // put object into the array
obj = {}; // new empty bject
obj.a = 2;
obj.c_str = "whatever";
my.tmp.push(obj);
Or, you could assign each property individually like this:
my.tmp.push({}); // put empty object into the array
my.tmp[0].a = 1; // assign property to the object
my.tmp[0].c_str = "foo"; // assign property to the object
my.tmp.push({});
my.tmp[1].a = 2;
my.tmp[1].c_str = "whatever";
In either case, you could then access the data like this:
console.log(my.tmp[0].a); // 1
console.log(my.tmp[0].c_str); // "foo"

Categories

Resources