Variable value is not changing according to the variable - javascript

So here's the thing. I've declared the following variables to concat my object:
var newObj = obj[property];
var fullObj = newObj[id];
Then I'm matching the value of "fullObj" with the value of another obj named "Array". I do it like this:
fullObj = Array;
Then "fullObj" gets the new value, but the original object, which is something like: "obj.property.id" does not. Any ideas?
EDIT:
This is the function
function updateData(obj, Array, id, property) {
var newObj = obj[property];
var fullObj = newObj[id];
fullObj = Array;
}
The property that I'm sending back is "obj", with all its inner elements (obj.property.id).
As you can see, "fullObj" is the same thing as saying that last object construction. Imagine something like "object.id["0"]. So imagine the value of "Array" is "object.id["1"]. I'm giving "fullObj" that value by matching them both, but the original object won't get it.
Am I being clear enough?

The problem is that you are re-assigning the value for the fullObj variable. You can access the referenced object like that, but you can't change it.
Anyway, i don't see the point of doing that the way you are doing it. You can assign the value directly like this:
function updateData(obj, Array, id, property) {
obj[property][id] = Array;
}

You changed the reference of fullObj to some other reference (Array). The reference of newObj[id] remains the same.
Example
var a = [1];
var b = a;
b = [2];
console.log(a, b); // it logs [1] [2]

Related

Add a child to a JavaScript object with a variable name

Let's say I have a blank JavaScript object:
myObject {}
And I also have a variable:
var myChildObject = this.name.split('.')[1];
For the sake of an example, let's say that myChildObject equals "FooBar". Now, I want to add a child object to myObject with the name of "FooBar", only we can't hard code "FooBar". We have to use the variable name myChildObject.
I tried this:
myObject.appendChild(myChildObject);
That doesn't work.
The goal is this:
{
"myObject":{
"FooBar":{
"thing1":25,
"thing2":6
},
.....
}
But I need to build the entire thing dynamically, without the names (other than the root) being known ahead of time.
An object is a "key value" type of thing, a little bit like a Map in Java. have you tried something like this:
let myObject = {};
let myChildObject = "fooBar";
myObject[myChildObject] = {};
This way you have a "fooBar" key for your Object... now you have to decide what you want the value to be for that key.
Objects can only have key value pair. You cannot use one without other. If you don't want to assign a value then simply give undefined. If you don't know the name of the property then you can simply use the array type notation for an object "[]". Refer to code below
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] = undefined;
console.log(myObject.hasOwnProperty(myChildObject)); // true
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] ={
"thing1":25,
"thing2":6
};
I'd say
for(var key in myChildObject) {
myObject[key] = myChildObject[key]
}
No idea what your question means but myObject["foobar"] might be what you are looking for

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);

How to access property in object according to array

so i have an array like this:
var arr=[one, lol];
and an object like this
var obj={
one:{
lol:11234
}
}
How do I make it so if i do obj[lol] then it will print out 11234? Keep in mind I don't know how long the array is and answers like console.log(obj[one][lol]) doesn't work. Thanks in advance.
You can store the previous property's value (initially obj) and continue to loop until end of array like so:
var arr = ['one', 'two', 'three'];
var obj = {
one: {
two: {
three: 11234
}
}
}
var currentProp = obj;
for(var i = 0; i < arr.length; i++) {
currentProp = currentProp[arr[i]];
}
console.log(currentProp);
The above code will start at the object obj, then loop until the array's length, and reassign currentProp to the next property in the array as it goes. In this case, this is what it does:
First iteration, access obj[arr[0]], which is one, and assign it to currentProp
Second iteration, access obj[arr[0]][arr[1]] or one[arr[1]], which is two, and assign it to currentProp
Third iteration, access obj[arr[0]][arr[1]][arr[2]] or two[arr[2]], which is three, and assign it to currentProp. Loop then terminates as it has reached end of the list.
In the end, the value of the last property will be in currentProp, and will correctly output 11234.
You need to try like this :
obj["one"]["lol"]
JsFiddle : https://jsfiddle.net/3we2ohy6/1/
Since you are just looking up a property value it is simpler to do:
console.log(obj.one.lol);
Doing it using the square brackets the way you have it JS thinks both the one and LOL are variables. Unless you wrap them in quotes.
console.log(obj['one']['lol');
You will not get to the value you are looking for the way you are doing it unless you create a function that either restructures the obj object or you feed it the obj.one as a property.
You could use Array#reduce, because this returns the object you need, without keeping a reference outside.
function set(object, path, value) {
var last = path.pop();
path.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var obj = {};
set(obj, ['one', 'lol'], '11234');
console.log(obj);

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

How did the value of Object Array in javascript be operated?

I feel puzzled when I rethink of these two functions:
The first one goes like this:
var test = [1,2,3];
var ele = test[0];
ele= 2;
alert(test[0]);
The result is 1. I think this is obvious. But when I meet this:
var test = [{id:1},{},{}];
var ele = test[0];
ele.id = 2;
alert(test[0].id);
The result turns to be 2
So could anyone tell me that how the javascript work when it happens like this in the object array?
In JavaScript, objects are assigned by reference, rather than copied in memory. So if you assign an existing object to a different variable, both will point to the same object in memory. Modifications to either will therefore be reflected in both.
var a = {id: 1, name: "bob"};
var b = a;
console.log(b.name); // bob
b.name = "bill";
console.log(a.name); // bill
So in your example, executing ele.id = 2; operates on the memory location holding the object at test[0]. The change to the id property of that object is reflected in both variables referencing it (test[0], ele)
Note that if you had assigned the entire array test to ele, modifying one of the array members would have been reflected in both test, ele since Arrays are objects in Javascript:
var test = [1,2,3];
// Assign array test to ele
var ele = test;
// Modify one member
ele[0] = 2;
alert(test[0]); // 2

Categories

Resources