duplicate the object and then update a value in JSON object - javascript

I have a array of json objects in jquery . I want to duplicate a object and then replace key value in original object on the basis of if condition . but every time i replaced the value in single object then it replaced the values in both objects . I only want to replace in one i.e original
I have used break and return false statements but dont work.
var index=getIndex(class_id,teacher_id);
finalJson[index]['teacher_name']='asad';
function getIndex(class_id,teacher_id){
for(var it in finalJson){
if(finalJson[it]['class'] == class_id && finalJson[it]['type'] == 'c'){
finalJson.push(finalJson[it])
return it;
}
}
}
please anybody help here is if condition .
Thanks in advance.

When you do finalJson.push(finalJson[it]) you are pushing the reference to old object again in the array. So, any operation done on one reference will be performed on the object to which new reference is pointing to. Which is why you need to create a new object using the properties of old one (using Object.create) and then push it.
replace
finalJson.push(finalJson[it])
with (don't use this option)
finalJson.push(Object.create(finalJson[it]))
or a slower but deep-copy option
finalJson.push(JSON.parse(JSON.stringify(finalJson[it])));

When you copy the object to a new variable, you are creating a reference. You need to create a new object to prevent this, otherwise the changes applied to one object will apply to the other.

Related

Is it possible to modify a value in a Set

Using a JavaScript Set, is it possible to modify a value previously added?
For example:
const mySet = new Set()
mySet.add(42)
mySet.set(0, 69)
.set is made up, I just want to modify the set at index 0. Is there any way to do this or should I be using a regular array or even a Map?
No, you have to remove it and readd the appropriate value. Sets only contain values, nothing more.
Sets don't have an index. You can use a Map or object, as you suggested.

JS is changing 2d-array values, might it be another function interfering?

Short summary: I have written some code that fills up a 2-dimensional array. When I display this array, everything is perfect. Now I give this 2d-array as a parameter to a function. When I call the function inside of
document.getElementById('output').innerHTML = myFunction(int, array);
it shows exactly the right values. However, I don't want to display them, I want to further use them. As the function returns an array (one dimensional), I tried
var my_result_array = myFunction(int, array);
I have also tried push() and pre-defined arrays or accessing just single elements.
The thing is, as soon as I have the function called in my document, the array I am giving to the function as a parameter is changing! I took care that there are no similiar names, but I just can`t figure out, why it is always changing my parameter array, therefore destroying the calculation but working fine if I use it in the document.getElementbyId part.
Any suggestions?
Edit for more code:
I try to keep it short and explainatory. I am creating an empty array with a dimension given by mat_dimension_js
var berechnungs_array = new Array(mat_dimension_js);
for (var i = 0; i < mat_dimension_js; i++){
berechnungs_array[i] = new Array(mat_dimension_js);
}
I then fill this array up with values. If I print the array, everything is fine, the values are where they belong. I then feed this array to myFunction()
Sorry for the mess, I have also tried it without creating an array A again.
I then try to grab the output of myFunction() as told above, but as soon as I do that, somehow the array I have given as a parameter changes.
Arrays in JavaScript are passed by reference, meaning that any changes you do to the array passed inside the function will also be saved in the actual array.
In addition, A = mat_array; does not create a copy of mat_array, but another pointer to it (meaning that both variables refer to the exact same array object internally).
To properly make a copy of a 1D array, calling .slice(0) should do the trick. However, for 2D arrays, you need to do this recursively.
See Javascript passing arrays to functions by value, leaving original array unaltered
What is the most efficient way to deep clone an object in JavaScript?

How to check if an array of string elements is found inside another array with jQuery.inArray()?

I have a <SELECT multiple="multiple"> box with options.
I store the selected options in a JS variable - selectedFeatures.
I want to pass selectedFeatures array variable of options to jQuery.inArray() - but the function is designed to take and check for one value only.
I can show/hide( or filter ) the markers on my map if I actually specify an index of an element like so: selectedFeatures[0] inside inArray()
..but since I may select multiple options from a select box this method of filtering doesn't work.
How can I check if an array of items in found inside another array with JS/jQuery?
// store selected options as an array of string elements inside the variable
var selectedFeatures = $("#features").val();
// for every element inside 'markers.houses' array...
$(markers.houses).each(function(index, elem){
// check if any of the values inside the 'selectedFeatures' array are found
// also inside a sub-array 'features' inside every element of 'markers.houses'
// array. if 'true' show that particular marker, otherwise hide the marker
if(jQuery.inArray(selectedFeatures, elem.features) !== -1 || jQuery.inArray(selectedFeatures, elem.features) > -1){
markers.houseMarkers[index].setVisible(true);
}else{
markers.houseMarkers[index].setVisible(false);
}
});
Fig 1.1 - store selected options in an array variable and use it with jQuery.inArray()
What you are asking for can be solved with PHP's array_diff function. I know you're not using PHP, but that's why there is array_diff on PHPJS, a project dedicated to porting PHP functions into JavaScript.
Anyway, to solve this you basically want to call array_diff(selectedFeatures,elem.features).length == 0. (You may need to swap the arguments around, I'm not sure which array is which in your question)
array_diff returns the elements of the first array that are not present in the others. If all of the elements in the first array are also in the second array (ie. array1 is a subset of array2), then the returned array will be empty, hence its length is zero.
Check this library: underscore.js
And you could use _.difference(array, *others).
Or you can create your own function to check if values from one array are in another array.

handling splice with associative arrays in javascript

I have an array called as wcs declared using var wcs= new Array();.
I do add items like this, wcs[indx] = value. where i will keep on changing the indx value, so at times, my array will be looking like this
wcs[2] ='a'; wcs[5]=')';
when i call the splice method on this array, all the created indices are re-indexed, meaning they become reset from 0...
how to avoid this in javascript & jQuery
Write your own splice method that works the way you want. If you specify the input, processing and expected output, you might get some help with that.
If you simply want a copy of the array, you may be after the concat method.

How come setting value in one array key is setting in another key?

I have an array of objects with various objects within to hold UI values. I wanted to have a button so that element 0's values are replicated through the whole array. However I noticed that setting one set them all. Here is an example without using any looping:
console.log('manual 3: ', lis[3].spacer.divider.type); // prints 'none'
lis[1].spacer.divider.type = 'bananas';
console.log('manual 3: ', lis[3].spacer.divider.type); // prints 'bananas'
I am completely baffled how setting lis[1] also set lis[3]
They must both be references to the same object.
If they're DOM nodes, you can copy them using cloneNode().
Watch out for IE bugs - it has a habit of not cloning properly (for example cloning a <select> doesn't maintain the selectedIndex).
See also What is the most efficent way to clone a JavaScript object? for cloning objects.
Because the variables are reference variables and they all reference the same object and as a result it looks like changing one changes all of them, really they are all the same underlying object.
If you want lots of unique arrays they should all be created as a fresh or be clones of each other.
It turns out I was referencing the same object. Thanks. It didn't click to me since all the other objects above (spacer,lis) were unique. I accidentally was setting divider to a member default of spacer instead of a function returning the default.
Thanks!

Categories

Resources