I am serializing a form and trying to change some values in this object but it never changes.
So I used a test variable for check this and when I am monitoring, this isnt changes too.
var invoice = _$form.serializeFormToObject();
var test = { ContainerNumber: "TEST" };
var collectedContainerNumbers = JSON.parse(invoice.CollectedContainerNumbers);//["ABCD 123456-7","DEFK 231120-0","DNME 222222-2","DNME 321321-3","MACA 010220-2","OKLS 121212-1","TEST 000000-0","TeSt 123456-1","TeSt 123456-6","TeSt 123456-7","TEST 131313-1","TEST 150150-0","TEST 181818-1","TEST 222222-7","TEST 231114-1","TEST 232223-3","TEST 245680-2","TEST 333333-3","TEST 357913-5","TEST 444444-4","TEST 828282-8","TEST 999999-9"]
$.each(collectedContainerNumbers, function (index, value) {
invoice.LogisticFileId = '';
test.ContainerNumber = value;
console.log(test);
});
It is a console result. I am seeing a thing like a title and it is changing but content isnt changing.
It looks like very simple but I don't understand the mistake that I am making.
Edit you will need an array instead of object to send all values to backend. Try converting your test object as an array like below.
var invoice = _$form.serializeFormToObject();
var test = []; // declare test as an array.
collectedContainerNumbers = JSON.parse(invoice.CollectedContainerNumbers);
$.each(collectedContainerNumbers, function (index, value) {
invoice.LogisticFileId = '';
test.push({ContainerNumber = value}); // push value in an array
console.log(test);
});
Try this thing in console it might solve your confusion. Add an object like let test = { ContainerNumber: 'ABCD 123456-7' }. Then log it in console. Do not expand right now. Now change the value of test.ContainerNumber = 'TEST 000000-0';. Now log the object & expand both logs. In first log also when you expand it will display { ContainerNumber = 'TEST 000000-0' }. as it is fetching current values when we expand.
You can also log ContainerNumber and check what exactly values hold by test.ContainerNumber. Like in below snippet. It will show you when you do console.log(test.ContainerNumber); first time it will show ABCD 123456-7 and second time it will show TEST 000000-0 which is as expected.
Try with below like. 1. Open console of browser. 2. Click on Run Code Snippet. 3. Expand object in console.
let test = { ContainerNumber: 'ABCD 123456-7' };
console.log(test);
console.log(test.ContainerNumber); // Output "ABCD 123456-7"
test.ContainerNumber = 'TEST 000000-0';
console.log(test);
console.log(test.ContainerNumber); // Output "TEST 000000-0"
Check browser console.
I have this code
var obj = [];
$('#next').click(function(){
jQuery.getJSON(produk1 , function(product1) {
hargana1 = product1.price;
obj.push({
harga: hargana1
});
}
jQuery.getJSON(produk2 , function(product1) {
hargana2 = product2.price;
obj.push({
harga: hargana2
});
}
console.log(harga)
});
And I have result on my console like this
How can I get value from harga?
I try with obj['harga'] It shows undefined
Well if you take a closer look then you will see that this is actually an array filled with objects. you can see that its an array by the brackets []
Try it like this: obj[0].harga
You should iterate through the array :
const out = [{harga:21132424},{harga:543535}]
console.log(out)
out.forEach(obj=>{
const harga = obj.harga;
//do something to harga here
console.log(harga)
})
I search on stackoverflow before post my question, but I didn't find any solution. I have an object like this :
"{"COURRIERS":
{"05. Juridique":
[{"res_id":100,"type_label":"Plainte","subject":"test23","doctypes_first_level_label":"COURRIERS","doctypes_second_level_label":"05. Juridique","folder_level":2}]
}
}"
And I need to access it like an array, in order to get the information like res_id etc..
How can I do this ?
Thanks in advance
Assuming that you won't have more than one object/array in each layer, this should get you what you need.
let obj = {
"COURRIERS": {
"05. Juridique": [{
"res_id": 100,
"type_label": "Plainte",
"subject": "test23",
"doctypes_first_level_label": "COURRIERS",
"doctypes_second_level_label": "05. Juridique",
"folder_level": 2
}]
}
}
let folder = Object.keys(obj)[0]
let type = Object.keys(obj[folder])[0]
let result = obj[folder][type][0]
console.log(result)
You can gain access to the data in multiple ways. The following below will help clarify some of the way you can access some of the data.
myObj.type = "Dot syntax";
myObj.type = "Dot syntax";
myObj["date created"] = "String with space";
myObj[str] = "String value";
myObj[rand] = "Random Number";
myObj[obj] = "Object";
myObj[""] = "Even an empty string";
For your problem you can use the following
var x = {
"COURRIERS":{
"05. Juridique":[
{
"res_id":100,
"type_label":"Plainte",
"subject":"test23",
"doctypes_first_level_label":"COURRIERS",
"doctypes_second_level_label":"05. Juridique",
"folder_level":2
}
]
}};
console.log(x['COURRIERS']['05. Juridique'][0].res_id)
Something like that ?
(I insert the data inside a variable and print the wanted result with key index)
let obj = {
"COURRIERS":{
"05. Juridique":[
{
"res_id":100,
"type_label":"Plainte",
"subject":"test23",
"doctypes_first_level_label":"COURRIERS",
"doctypes_second_level_label":"05. Juridique",
"folder_level":2
}
]
}
};
console.log(obj["COURRIERS"]["05. Juridique"][0]["res_id"]);
EDIT
You want to acess it with variable.
For avoid bug, I strong recommend you to check if the variable value key exist in the array/object like :
let folder = 'COURRIERS';
if(folder.indexOf(data) >= 0) { // folder.indexOf(data) = 0
// ... finish the job here :)
}
// indexOf return -1 if the value is not found
I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?
I am trying to use two json file. One for taking the data type of data and other for getting the data value of data.
Since I don’t know how to use two json file in one so I stored one json values in a variable.
var data = {
“name”: “classxyz”,
“number”:”abc”,
Fields : [
{
“name”: ”studentname”,
“marks”:”int”
“doc”: “failed”
}
]
}
Second json file “student.json”
{
“datasvalue”:
[
{
“studentname”: “Jack”,
“marks”: “18”,
“place”: “newyork”
},
{
“studentname”: “sparrow”,
“marks”: “12”,
“place”: “london”
}
]
}
I want to take the value of data type from the first json and check it into the second json and then show the value of that data type which is taken in first json.
Example: From the first json I search name is “studentname” and now I want to print this “studentname” as a label and search it in the second json file (student.json) and print its value(sparrow) in front of studentname in textfield.
When I print the “marks” it should check from the first json file that it has “int” type and search its value from student.json value that is 18. If I try to put any other value it should not let me enter.
So far, I am able to do the following which is far away from what I have to do.
Can’t we use two json in one program? And why the .inArray is not working this way?
function ViewData()
{
function toArray(obj) {
var result = [];
for (var key2 in obj) {
var value = obj[key2];
result.push(key2);
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
$('#stage').append('<p>'+ key2+' : '+ "<input id=\"txtv\" type=\"text\" value=\""+value+"\"/>");
}
return result;
}
var arra =[];
arra = JSON.strigify(toArray(data));
$('#stage1').html('<p>'+arra + "<br>"+'</p>');
//$('#stage1':contains('day'));
}
$.getJSON('student.json',
function(datas)
{
// Create an array to hold the data.
var items = [];
var storeName=[];
var storeValue=[];
// Parse the data by looking at each entry in the dates object.
$.each(datas.datasvalue,
function(key1, value1)
{
var i=0;
$.each(value1, function(key,value){
storeName[i]= key;
storeValue[i] = value;
$('#stage2').each(function(){
// if($.inArray(key.text(),arra)){
alert($.inArray(key,arra));
$(this).append('<p>'+ key+' : '+ "<input id=\"txtv\" type=\"text\" value=\""+value+"\"/>");
// }
}); // end of stage each funtion
i++;
}); // end of value and key funtion
}); // end of value1 function
}); // end of function (data)