Related
How to modify this to add two text boxes value to the URL.
//to add append single input value.
function filter(){
var myInput1 = document.getElementById('myInput1').value;
var searchType="fileName"
var appl="www.google.com/search/?"+searchType+"="+myInput1;
console.log(appl);
myInput1.href =appl;
myInput1.innerHTML = myInput1.href;
window.location = "www.google.com/search/?"+searchType+"="+myInput1;
}
Thanks in advance.
You can create an array that contains a map of parameters name and values, and then join everything together to get your query string, something like:
var parameters = [
[ "fileName", document.getElementById('myInput1').value ],
[ "otherInput", document.getElementById('myInput2').value ]
];
var query = parameters.map(function(couple) {
return couple.join("=");
}).join("&");
// if you can use ES6 can be shorter, like:
// var query = parameter.map(couple => couple.join("=")).join("&");
var url = "www.google.com/search/?" + query;
Input of Json Object:
{"data":[
{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},
{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}
]}
Expected Output of Json Object:
[{
"itemID":"100",
"Testcase1":"aaa",
"Testcase1":"bbb",
"Testcase1":"ccc",
"status":"Active",
"status":"No",
"status":"Active"
},
{
"itemID":"101",
"Testcase1":"zzz",
"status":"Active"
}]
anybody help me?
may be this helps you. This is not the correct way. Because duplicate key is not allowed in object. whatever as it your request. I have create a string of your required format.
please checkit FIDDLE
var dataVal={"data":[
{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},
{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}
]};
var arrayVal = dataVal.data;
var DistinctID=[];
var resultStr="";
for (var elements in arrayVal){
if($.inArray(arrayVal[elements].itemID, DistinctID) == -1){
DistinctID.push(arrayVal[elements].itemID)
}
}
for (var items in DistinctID){
resultStr +='{"itemID":"'+DistinctID[items]+'",';
for (var elements in arrayVal){
if(arrayVal[elements].itemID==DistinctID[items]){
resultStr +='"Testcase1":"'+arrayVal[elements].Testcase1+'",';
resultStr +='"status":"'+arrayVal[elements].status+'",';
}
}
resultStr = resultStr.substring(0, resultStr.length - 1);
resultStr= resultStr+'},';
}
resultStr = resultStr.substring(0, resultStr.length - 1);
resultStr='['+resultStr+']';
alert((resultStr));
Assuming your "JSON Object" is a string, you can call JSON.parse() on it:
var data = '{"data":[{ ... }]}';
var parsed = JSON.parse(data);
This will give you data in the following structure:
Your expected output isn't a valid object. Object keys must be unique. An object cannot have three Testcase1 keys or three status keys.
You just have to extract objects from data object ?
Ok then, a pure JS solution :
var obj = {"data":[{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}]};
var newArray = [];
for( var i = 0; i < obj['data'].length; i++) {
newArray.push(obj['data'][i]);
}
And a live demo of that : http://jsfiddle.net/seLwmbyp/1/ (see the console for the result) > [Object, Object, Object, Object]
Hi i have a Json like below format .I want to replace the value of text:"Sample Text" Sample text with a value from My array in js file.
JSON Format
prx.xdata = {"cc":6,
"symbols":[
{
"id":1,
"title":"news container",
"states":[
{"title":"Default State",
"background":"none",
"data":"[{\"name\":\"text\",\"type\":\"text\",\"lib\":\"common\",\"caption\":\"newsitem1\",
\"text\":\"Sample text\",\"textFont\":\"sans-serif,Helvetica Neue,Arial\",\"textSize\":\"16\",
\"textColor\":\"000000\",\"backgroundColor\":\"none\",\"width\":292,\"height\":257,\"textProperties\":[],
\"textAlign\":\"left\",\"enableShadow\":false,\"autoResize\":false,\"left\":8,
\"top\":21,\"vpos\":\"top\",\"hpos\":\"left\",\"visible\":true,\"id\":\"box-2\",
\"groups\":[],\"zindex\":2001,\"wtype\":\"fixed\",\"htype\":\"fixed\",\"opacity\":\"1\"},
{\"name\":\"text\",
\"type\":\"text\",\"lib\":\"common\",\"caption\":\"news item2\",\"text\":\"Sample text\",\"textFont\":\"sans-serif,Helvetica Neue,
Arial\",\"textSize\":\"16\",\"textColor\":\"000000\",\"backgroundColor\":\"none\",\"width\":301,\"height\":257,\"textProperties\":[],
\"textAlign\":\"left\",\"enableShadow\":false,\"autoResize\":false,\"left\":300,\"top\":21,\"vpos\":\"top\",\"hpos\":\"left\",
\"visible\":true,\"id\":\"box-3\",\"groups\":[],\"zindex\":2002,\"wtype\":\"fixed\",\"htype\":\"fixed\",\"opacity\":\"1\"},
{\"name\":\"text\",\"type\":\"text\",\"lib\":\"common\",\"caption\":\"news item3\",\"text\":\"Sample text\",
\"textFont\":\"sans-serif,Helvetica Neue,Arial\",\"textSize\":\"16\",\"textColor\":\"000000\",
\"backgroundColor\":\"none\",\"width\":292,\"height\":257,\"textProperties\":[],\"textAlign\":\"left\",
\"enableShadow\":false,\"autoResize\":false,\"left\":601,\"top\":21,\"vpos\":\"top\",\"hpos\":\"left\",
\"visible\":true,\"id\":\"box-4\",\"groups\":[],\"zindex\":2003,\"wtype\":\"fixed\",
\"htype\":\"fixed\",\"opacity\":\"1\"},
{\"name\":\"text\",\"type\":\"text\",
\"lib\":\"common\",\"caption\":\"news item4\",\"text\":\"Sample text\",
\"textFont\":\"sans-serif,Helvetica Neue,Arial\",\"textSize\":\"16\",\"textColor\":\"000000\",
\"backgroundColor\":\"none\",\"width\":298,\"height\":257,\"textProperties\":[],
\"textAlign\":\"left\",\"enableShadow\":false,\"autoResize\":false,\"left\":901,\"top\":21,
\"vpos\":\"top\",\"hpos\":\"left\",\"visible\":true,\"id\":\"box-5\",\"groups\":[],\"zindex\":2004,\"wtype\":\"fixed\",
\"htype\":\"fixed\",\"opacity\":\"1\"}]",
"history":[],"dimensions":["1200","300"],"id":"a8d0d79e-1921-4f7e-a229-75e5b1602881"
}]
,"sort":0,
"customguides":{"horizontal":[],"vertical":[]},
"grid":{"col_number":3,"col_width":80,"gutter_width":20,"margins":10}
}]
};
prx.xdata_str = JSON.stringify(prx.xdata);
I want to replace the value of "Sample text " in this path
symbols[0].states[0].data[0].text with value from News array.
Problem is here
symbols[0].states[0].data this data is another JSON ,so am not able to parse that data.
Please check my Js code
function yourJsFunction(arr){
var b=arr.toString().split(',');
var News =new Array();
News=b;
var jsondata = JSON.parse(prx.xdata);
//alert(jsondata.symbols[0].states[0].data);
var data=new Array();
data=jsondata.symbols[0].states[0].data;
// alert(data);
var newData=JSON.parse(data);
newData[0].text=News[0];
newData[1].text=News[1];
newData[2].text=News[2];
newData[3].text=News[3];
alert(newData[0].text);
//This alert showing my updated json.But when i click ok in alert the webview showing previous Json
jsondata.symbols[0].states[0].data= JSON.stringify(newData);
prx.xdata = JSON.stringify(jsondata);
for(var i=0;i<arr.length;i++){
// document.write(arr[i]);
}
}
var x = "{a: 'a', b: 'b'}" this is an json string
var o = eval('"' + x + '"') o is json object, parsed.
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 have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");