push JSON object to array is not adding in array - javascript

I have a problem I don't know what am doing wrong, below code need to push and JSON Object into array but its not updating, its only showing last pushed element.
var myData = {};
var id = 0;
$("a").on('click', function(){
myData.answers = new Array();
myAns = { id : id, answer : "my answer" };
myData.answers.push(myAns);
id++;
console.log(myData);
});
Here is a Fiddle for same, please help

Move myData.answers = new Array(); out of the click event handler. You're reseting the array every time you click the link:
myData.answers = new Array();
$("a").on('click', function(){
myAns = //etc

Related

Push an object to array, obejct overwritting the previos one

I am trying to push the object resultOBJ to the array resultArray
when the button "Добавить обозначение" is clicked.
first object has been sent well, the data is the same what I am looking for, but when I push another object the second object is rewriting the previous one, the third object is rewriting the first and the second and so on.
here is my code. Please, tell me what I am doing wrong.
Thanks in advance.
var color = {red:"#ff0000",purple:"#990099",green:"#33cc33",yellow:"#ffff00",blue:"#0000ff",orange:"#ff8000",pink:"#ff0080",
skyblue:"#00ffff",black:"#000000",gray:"#808080",brown:"#4d1f00"};
var diams = ["60","65","68","69","70","75","76","80","81","82","85","90"];
//show hidden elements
$(document).ready(function(){
$("#addRowDDL").click(function(){
$("#DDL,#deleteRowDDl,#useIt").fadeIn("slow");
});
});
var resultOBJ=new Object();
var resultArray = new Array();
var finalobj = {} ;
var obj = new Object();
function addDropDownLists(){
var myObject = $("#htmltoget").children().clone();
$("#DDL").append(myObject);
$.each(diams,function(key,value){
myObject.find(".chooseDiams").append($("<option></option>").attr("value",key)
.text(value));
});
$.each(color,function(key,value){
myObject.find(".chooseColor").append($("<option></option>").attr("value",key)
.text(key));
});
myObject.find(".chooseColor").change(function(){
displayColors(this);
});
myObject.find(".chooseDiams").change(function(){
displayDiams(this);
});
resultArray.push(obj);
}//End of addDropDownLists function
function displayColors(param){
var colorValues = $(param).val();
resultOBJ.color=colorValues;
}
function displayDiams(param){
var diamsValues = $(param).val() || [];
resultOBJ.diams=diamsValues;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="htmltoget" style="display: none;">
<div class="DDL-Con">
<div class="diams">
<p>Диаметр</p>
<select class="chooseDiams" multiple>
<option selected hidden> Выбрать Диаметр</option>
</select>
</div>
<div class="color">
<p>Цвет</p>
<select class="chooseColor">
<option selected hidden>Выбрать Цвет</option>
</select>
</div>
</div>
</div>
<button type="button" id="addRowDDL" onclick="addDropDownLists()" style="margin-bottom: 20px;">Добавить обозначение</button>
<div id="bigwrapper">
<div id="DDL">
</div>
</div>
</body>
Having a hard time telling what you're trying to accomplish but you push obj which is empty and should be giving you an array of empty objects.
Also, you need to create a new object for each call of addDropDownLists() otherwise you are just passing a reference and the changes will effect every object in the array.
//show hidden elements
$(document).ready(function(){
$("#addRowDDL").click(function(){
$("#DDL,#deleteRowDDl,#useIt").fadeIn("slow");
addDropDownLists();
});
});
var resultArray = new Array();
function addDropDownLists(){
var resultOBJ=new Object();
var myObject = $("#htmltoget").children().clone();
$("#DDL").append(myObject);
$.each(diams,function(key,value){
myObject.find(".chooseDiams").append($("<option></option>").attr("value",key)
.text(value));
});
$.each(color,function(key,value){
myObject.find(".chooseColor").append($("<option></option>").attr("value",key)
.text(key));
});
myObject.find(".chooseColor").change(function(){
resultOBJ.color = $(this).val();
});
myObject.find(".chooseDiams").change(function(){
resultOBJ.diams = $(this).val() || [];
});
resultArray.push(resultOBJ);
console.log(JSON.stringify(resultArray));
}//End of addDropDownLists function
This setup does insert an empty object into the array the first time the button is clicked, or if there is no change. Not sure what you're trying to accomplish though so I left it as is.
Demo: https://jsfiddle.net/3p37znq1/2/
You don't push resultOBJ, you push obj which is always empty as you don't do anything with it after initialization.
When you push obj each time you just push a reference to the same instance instead of creating a new one. Any change to obj will affect all items in resultArray.
In change handler you always update the same instance of resultOBJ and this update always overwrites previous change. Actually, the values in this object mean "last selected color anywhere" and "last selected diam anywhere".
Something like this should work:
var resultArray = [];
function renderOption(value, name) {
var option = document.createElement("option");
option.value = value;
option.innerHTML = undefined === name ? value : name;
return option;
}
function updateResult(index) {
var item = resultArray[index],
node = document.querySelector("#DDL").childNodes.item(index);
item.diam = node.querySelector(".chooseDiams").value;
item.color = node.querySelector(".chooseColor").value;
}
function addDropDownLists() {
var container = document.querySelector("#DDL"),
index = resultArray.length,
changeHandler = updateResult.bind(null, index),
tpl = document.querySelector(".DDL-Con"),
node = tpl.cloneNode(true),
list, key, len
;
list = node.querySelector(".chooseDiams");
for (key = 0, len = diams.length; key < len; key++) {
list.appendChild(renderOption(diams[key]));
}
list.onchange = changeHandler;
list = node.querySelector(".chooseColor");
for (key in color) {
list.appendChild(renderOption(key, color[key]));
}
list.onchange = changeHandler;
container.appendChild(node);
resultArray.push({
diam: null,
color: null
});
updateResult(index);
}
PS: Sorry, I see you use jQuery... I'm too lazy to remember it's API. Haven't used it for a long time. Hope, you'll catch the main idea.
PPS: if you plan to delete items, maybe it's better to bind the whole node and search for it's index via isSameNode() method. Bound indexes will become invalid after removing item, they will shift.

Push values to array in jquery

I have List of items data and empty array quotations :
var data = {};
var quotations = [];
I want to fill quotations with data values ,Every time i add new data it added successfully but all data values get last value .
for example :
$("#addquotation").click(function () {
debugger;
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
for first time i add
"test,45,testnotes,2016-02-03" Second time i 've added
"test2,45.2,testnotes2,2016-02-05"
when i debug i get data as :
obj(0): "test2,45.2,testnotes2,2016-02-05"
obj(1):"test2,45.2,testnotes2,2016-02-05"
it seems it append last version to all data
Please Advice . Thanks
You need to declare data inside the click handler, if it's declared as a global variable you are basically always modifying and adding the same data object to the array:
var quotations = [];
$("#addquotation").click(function () {
debugger;
var data = {};
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
You are pushing the same object reference each time since you declared data outside of the click handler.
Change from :
var data={};
$("#addquotation").click(function () {
To
$("#addquotation").click(function () {
var data={};// declare local variable
The problem is that data is a global variable and you add a reference to data to quotations.
When the first value is pushed to quotations, data and quotations[0] refer to the same object. Here is an example of what is happening:
var a = {num: 1};
var b = a;
b.num = 2;
console.log(a.num); // prints 2
The same thing happens when an object is pushed to an array. quotations does not contain a copy of data, it contains a reference to data so that modifying data also modifies quotations. To fix this, each element of quotations must refer to a different data object. This can be accomplished by defining data inside of the function instead of outside.
Replace
var data = {};
$("#addquotation").click(function() {
// populate data, push to quotations
});
with
$("#addquotation").click(function() {
var data = {};
// populate data, push to quotations
});

Iterate through Id's, store values, put into an array

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").
Then I need to get the values of the those options, put into an array called arraylist.
$("#doThis").on("click", function() {
var optionone = $("#option1").val();
var optiontwo = $("#option2").val();
var optionthree = $("#option3").val();
var optionfour = $("#option4").val();
var optionfive = $("#option5").val();
var arrayList = [optionone, optiontwo, optionthree,
optionfour, optionfive];
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event
As Andy said, give every option the same class. In my example it's "option-item".
$("#doThis").on("click", function() {
var arrayList = [];
$('.option-item').each(function(i) {
arrayList[i] = $(this).val();
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
});
Every value is now stored in the array.
see fiddle.
greetings timmi
With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:
$("#doThis").on("click", function () {
var arrayList = [];
$('[id^="option"]').each(function (index, element) {
arrayList.push($(element).val() );
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

Javascript multidimensional array returns first value and then fails

I am couting all svg-Elements from my html document in the var anzahl_der_SVGs. that works fine and it returns me 3 as it should. now i want to make a multidimensional array where i am going to store serveral svg-Element information. the structure is
[0][0] -> html code of svg
[0][1] -> id of a parent container
the javascript code is:
function getSVG(){
var anzahl_der_SVGs = $('svg').size();
alert(anzahl_der_SVGs);
var svgArray = new Array(anzahl_der_SVGs);
svgArray[0] = new Array(2);
$('svg').each(function( index ) {
id = $(this).parent().parent().parent().parent().attr("id");
var speichern = "widgetID" +id;
svgArray[index][0] = $(this).html();
svgArray[index][1] = speichern;
alert(svgArray[index][0]);
alert(svgArray[index][1]);
$(this).attr("id", speichern);
});
}
The alerts from the first iteration work fine and it shows me the svg html and the widget ID. in the next iteration it stops and gives me console output " TypeError: svgArray[index] is undefined " thx for any help :) best regards from germany
JavaScript doesn't have multi-dimensional arrays. What you've done is define a nested array for the first index of svgArray. What you need to do is define one for each member.
You can do that in the .each() loop.
$('svg').each(function( index ) {
if (!svgArray[index]) {
svgArray[index] = new Array(2)
}
Creating an array of object would be much simpler :
var svgArray = [];
var cpt = 0;
$('svg').each(function( index ) {
id = $(this).parent().parent().parent().parent().attr("id");
var speichern = "widgetID" +id;
svgArray.push({html: $(this).html(), id : speichern});
alert(svgArray[cpt].html);
alert(svgArray[cpt].id);
$(this).attr("id", speichern);
cpt++;
});

I want to insert values dynamically to hash map

var markerList1={};
var markerList=[];
and adding iterator values from the one for loop
function addSomething() // this function will multiple times from a for loop
{
image ='../css/abc/'+image[iterator]+'.png';
var data = respData[iterator];
var box = getbox(data);
var markerOpts = {
position : coordinates[iterator],
map : map,
icon :image,
title :data[1],
id : data[11]
};
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);
markerList1[markerOpts.title].push(vmarks);
}
whenever we call the function i want append the array's values to same index
markerList1[data[11]].push(vmarks);
but i'm not getting above result, when i markerList1[data[11]) then i'm getting only the last value i.e thirdvmark
i want output like this= markerList1[data[11]] = {firstvmark, secondvmark, thirdvmark};
You cannot do push to an object markerList1, only to an array.
change this
markerList1[markerOpts.title].push(vmarks);`
To this
markerList1[markerOpts.title] = vmarks;
markerList1[data[11]] is never initialized before you push something inside.
You can initialize it only once with a simple test:
if (! (data[11] in markerList1) ) {
markerList1[data[11]] = [];
}
markerList1[data[11]].push(vmarks);
Or in a shorter and safer way:
markerList1[data[11]] = markerList1[data[11]] || [];
markerList1[data[11]].push(vmarks);
(And please put data[11] in a variable)
Try this-
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);//you already pushing vmarks to array
markerList1[markerOpts.title]=markerList;//assign array to your markerList1 map

Categories

Resources