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
});
Related
There is a JSON file with an array like
{
"general_array":[
{"key_1":["a","b","c"]}
]
}
I want to add an element to the array e.g.
{"key_2":["d","e","f"]}
but the value of new key I get from a variable e.g.
var newKey = 'key_2';
I'm trying to add the element to the existed array as following
// ... getting file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
jsonObj.general_array.push({newKey:['d','e','f']});
var newJsonFileContent = JSON.stringify(jsonObj);
// and rewrite the file ...
// console.log(newJsonFileContent);
But in the file I get
{
"general_array":[
{"key_1":["a","b","c"]},
{"newKey":["d","e","f"]}
]
}
i.e. as the new element key I get the NAME of variable, but I need its VALUE
How to add the value?
UPDATED
The solution with [newKey] works in most of browsers, but it doesn't work in Internet Explorer 11
I need a solution to be working in IE11 too, so the question is still actual
You can use [newKey] to get the value of the variable as a key name:
var jsonFileContent = `
{
"general_array":[
{"key_1":["a","b","c"]}
]
}`;
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
var tempObj = {};
tempObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(tempObj);
var newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent);
To use the value of a variable as a JSON key, enclose it in square brackets, like so:
{[newKey]:['d','e','f']}
let jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
let jsonObj = JSON.parse(jsonFileContent);
let newKey = 'key_2';
jsonObj.general_array.push({[newKey]:['d','e','f']});
let newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent)
This is the computed property name syntax. It's a shorthand/syntax sugaring for someObject[someKey] = somevalue
Try changing this line:
jsonObj.general_array.push({newKey:['d','e','f']});
For this:
var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);
I have a problem adding the object "myobj" to the arrays data / data2. As you see "myobj" a JS object which I would like to add to either data or data2. the functions are being triggered by clicks on different buttons.
console.log of myobj shows me
{ array: "arr_id_1", axis: "x", acc: "", vel: "", dist: "", jerk: "" }
I receive an error saying data2.splice() is not a function.
which is the format I need. "myobj" is supposed to be added to an array which I want to use JSON.stringify on. This JSON literal goes then to a python script via ajax. The array "data" is being filled with each click I perform correctly but not in the format for further processing. So I tried to fill array data2 since I have read that I could use .splice() as well. Unfortunately, console.log(data2) shows "undefined" for each field I try to fill and I have no idea how to solve it.
I tried to use JSON.stringify on "myobj" and as another attempt, I have tried to JSON.parse it back again. I tried adding the brackets and colons into quotes but no success either.
I am grateful for any advice or help.
var counterx = 0;
let data = [];
let data2 = {};
function valuesX() {
counterx++;
// does something here
let arr_id = [];
arr_id.name = 'arr_id_' + counterx;
let ind = counterx - 1;
let myobj;
function arr() {
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value, btns.value, btnj.value)
myobj = {
array: arr_id[0],
axis: arr_id[1],
acc: arr_id[2],
vel: arr_id[3],
dist: arr_id[4],
jerk: arr_id[5]
};
console.log(arr_id.name, arr_id)
console.log(myobj)
console.log(data.name, data)
console.log(data2.name, data2)
}
data.name = 'data';
data2.name = 'data2';
data.splice(ind, 0, arr_id)
data2.splice(ind, 0, myobj)
}
SOLUTION:
I have converted the myobj to an object using Answer from JVE999, first suggestion and used .splice() to add the every new myobj to the array data. I have used splice because I need to overwrite already existing elements while keeping the order (Thus the indx) when I trigger the function (.splice() reference).
var arr_id = [];
arr_id.name = 'arr_id_'+counterx;
var myobj;
var indx = counterx-1;
var data_new;
data.name = 'data';
function arr(){
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value,btns.value, btnj.value)
myobj = {
array:arr_id[0],
axis:arr_id[1],
acc:arr_id[2],
vel:arr_id[3],
dist:arr_id[4],
jerk:arr_id[5]
};
data_new = convArrToObj(myobj);
data.splice(indx, 1, data_new)
data_str = JSON.stringify(data)
console.log(data.name, data)
console.log(data_str)
}
Every time I want to get the array from localStorage it only gets me the last value.I think it handles the array as a object. How do I fix this?
function saveData() {
if ($("#forma").valid() == true) {
var Name = document.getElementById("username").value;
var Year = document.getElementById("godinaupisa").value;
var Index1 = document.getElementById("brindeksa").value;
console.log(Name);
var EMial = document.getElementById("email").value;
var OBJ = { NAME: "JOHN DOE", YEAR: "18", INDEX1: "1", EMAIL: "#" };
OBJ.NAME = Ime1;
OBJ.YEAR = Year;
OBJ.INDEX1 = Index1;
OBJ.EMAIL = EMial;
var arrayOBJ = [];
arrayOBJ.push(OBJ);
localStorage.setItem("ARRAY", JSON.stringify(arrayOBJ));
alert("saved");
$("#forma").resetForm;
};
}
So, you're calling setItem which will just set it to whatever you pass it. I think what you want to go is read the current value, append to that and set the new value to be that.
var data = localStorage.getItem("ARRAY");
data = JSON.parse(data);
data.push(OBJ);
localStorage.setItem("ARRAY", data);
Because you create the arrayOBJ array each time you try to save, you're only ever going to have one item inside of it. And when you save it to localstorage you're just writing over anything that was already there. Instead try defining arrayOBJ outside your save function as a global variable.
Alternatively you can use localStorage.getItem and JSON.parse to get the current array that's in localStorage before pushing to it.
I am new to javascript so i dont know how to create object once we have values dynamically , so below code i have fullName and workerKey from dataItem now i want to create object selectedOwners with values of fullName and workerKey.
How can i achieve that task ?
ctrl.js
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
var fullName = dataItem.fullName;
var workerKey = dataItem.workerKey;
console.log('WORKER KEY', workerKey);
}
You use an object initializer:
selectedOwners = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
};
The object initializer is the {...} bit. Each of those two things inside it is a property initializer. The part before the : is the name, the part after is the value, which can be the result of any expression.
In your code, you'd already created the object (var selectedItem = {};). The code above will replace that object. If you just wanted to add to it, you'd just use assignment:
selectedItem.fullName = dataItem.fullName;
selectedItem.workerKey = dataItem.workerKey;
Which you use depends on whether it matters that you not create a new object.
Edited, as per comments:
var list = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwners = {"fullname":dataItem.fullName,"workerKey":dataItem.workerKey};
list.push(selectedOwners);
}
// use list to populate output
You have already created the object so all you need to do is add the values into it.
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
selectedOwners.fullName = dataItem.fullName;
selectedOwners.workerKey = dataItem.workerKey;
//This will print out the newly populated object
console.log(selectedOwners);
}
I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;