When i create a new object from an existing object, then append a new attribute, why does it update the earlier one?
Is their a solution that does not involve changing my code much?
Here is my example jsfiddle.
var data = [
{
"id" : 1,
"name" : "carrot",
"price" : 0.10,
"stock" : 12,
"bgLocation" : "-1px -54px"
},
{
"id" : 2,
"name" : "fennel",
"price" : 1.20,
"stock" : 6,
"bgLocation" : "-146px -52px"
}
]
var item = data[0];
item.added = 4;
//data[0] should not contain the added attribute.
$('body').append(JSON.stringify(data[0]));
The variables item and data are just references pointing to the same object. By calling.
var item = data[0];
you're not copying the object, you just create a new reference on the object that is addressed with data[0]. Therefore
item.added = 4;
will change the object bot vraiables point to.
Here
How do I correctly clone a JavaScript object?
are some detailed information on how to copy objects in javascript.
Because all you get is a reference to the original object, not a copy. Thus, if you update this reference, you are implicitly updating the original object.
You can easily create a copy using $.extend():
var item = $.extend({}, data[0]);
DEMO.
Related
How can I add {[]} in an array?
#CertainPerformance is correct. You have to have an associated property if you want to have objects.
var a = [ { propertyName : [] } ]
then you can access that array like this :
a[0].propertyName or a[0]['propertyName']
And you can have multiple values inside the object too :
var a = [
{
propertyName_1 : [],
propertyName_2 : "",
propertyName_3 : 3,
}
];
var a = [{}] // no problem, you are assigning an empty object `{}` as first element of array
var a = [[]] // no problem, you are assigning an empty array `[]` as first element of array
var a = [{[]}] // Not working because you're assigning empty array into object
//object needs key to store value
var a = {[]} //Not ok <<======== have you ever see var a = { 1, 2, 3} ?
Please refer to documentation:
An object is a collection of properties, and a property is an association between a name (or key) and a value.
I have an array as follows
[
[{"Id":"5","Color":"White"}],
[{"Id":"57","Color":"Blue"}],
[{"Id":"9","Color":"Brown"}]
]
each object is inside an array which is inside another array. I want to access an object item, let say 'Id' of first object ("Id":"5"). How can I do that?
If the array is assigned to a variable:
var a = [
[{"Id":"5","Color":"White"}],
[{"Id":"57","Color":"Blue"}],
[{"Id":"9","Color":"Brown"}]
];
You can do it like this:
a[0][0].Id;
or
a[0][0]["Id"];
To get the second object you would do:
a[1][0].Id;
or
a[1][0].["Id"];
if it's javascript your object must be named (e.g. x)
Then select the index of the first array (here : 0, 1 or 2)
Then the "small" array content only one item, you have no choice, take 0.
For end, you can pick the property you need, Id or Color.
You have :
var myColor = x[1][0]["Color"];
console.log(myColor); //output : Blue
var obj_c = [
[{"Id":"5","Color":"White"}],
[{"Id":"57", "Color": "Blue"}],
[{"Id":"9","Color":"Brown"}]
];
console.log(obj_c[0][0].Id);
console.log(obj_c[0][0].Color);
I have an object with dynamic properties. Each of these properties are removed and added based on some events. I want to have a function or property in this object which can return the array of values but having the same reference all the time. Whats the best way to do it?
For e.g if current state of the object is
var obj = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} }
var values = obj.someFunction()
values should be [{ 'name' : 'dark'}]
if current state of obj is
{"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}}
values should be [{ 'name' : 'dark'},{ 'name' : 'magic'}]
The reference of the array and the properties should never change (unless they are deleted).
How about this? It maintains the same array. If you want, you could also mix it in with the object, but would have to add a guard to not also add the function to the values.
var values = someFunction(obj, values);
function someFunction(obj, values) {
values = values || [];
values.length = 0;
for(var key in obj) {
values.push(obj[key]);
}
return values;
}
By the way, clearing the array by setting its length to 0 was gleaned from this post.
My might create a 'meta'-object that stores a reference to the original object and can return the values:
var Values = function(obj) {
this.getValues = function() {
var values = [];
for(i in obj)
values.push(obj[i]);
return values;
};
}
var original = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}};
var vals = new Values(original);
var values = vals.getValues();
Given that you seem to be generating the array within "someFunction" (seeing the code of the function and how you attach it to the object would help), you'll need to keep an instance of an array and empty/refill it rather than create a new one. It could be a member of your object (obj.currentItems) or within a closure (depending on how you create it), and it could be updated as you change its properties or on demand within someFunction.
I'll update my answer if you provide more specific code.
may I know how to push var obj= [{}] in .each? for example like this.
$.each(maintasks_row, function(index, maintasks_val) {
obj.push([{
"name" : maintasks_val.task_name,
"desc" : "",
"values" : [{
"from" : "/Date("+maintasks_val.time_start+")/",
"to" : "/Date("+maintasks_val.time_end+")/",
"label": maintasks_val.task_name,
"customClass" : "ganttRed"
}]
}]);
});
I'm using this for $(".gantt").gantt({source: obj});
On this site the var data is [{}] is this an object? and how can I insert it?
thank you
.push does not require you delcare it as an array ( like you tried obj.push([{ - unless of course you are pushing an array into an array
Just simply ...
obj.push({"name" : maintasks_val.task_name, ..
adds a new single item intto the array
Update as comment , yes, declare obj as a typeof array first
var obj=[];
This is now the same as the data array you have shown in your docs example - and we can now .push() into it.
I want to get first file name (Apple_Desk_1920 x 1200 widescreen.jpg) in the array img declared below. How do I do this?
This is my code:
var img = [{
"image" : "Apple_Desk_1920 x 1200 widescreen.jpg"
}, {
"image" : "aa.jpg"
}, {
"image" : "auroracu4.jpg"
}, {
"image" : "blue-eyes-wallpapers_22314_1920x1200.jpg"
}, {
"image" : "blue-lights-wallpapers_22286_1920x1200.jpg"
}, {
"image" : "fuchsia-wallpapers_17143_1920x1200.jpg"
}, {
"image" : "leaves.jpg"
}, ];
It's:
var variableName = img[0].image;
What you have there is an array of objects. To get an array entry, you use [] with an array index (0 to one less than the length of the array). In this case, that gives you a reference to the object. To access an object's properties, you can use literal notation as I have above (obj.image), or using [] with a string property name (obj["image"]). They do exactly the same thing. (In fact, the [] notation for accessing object properties is what you're using when you "index" into an array; JavaScript arrays aren't really arrays, they're just objects with a couple of special features.)
So breaking the line above down:
var variableName = // Just so I had somewhere to put it
img[0] // Get the first entry from the array
.image; // Get the "image" property from it
// dot notation
console.log(img[0].image);
or:
// square-bracket notation
console.log(img[0]['image']);
will get it for you, since you have an array of objects.