The result of my php is
$result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}]';
and done json parse to it
var data = new Array();
data = JSON.parse('<?php echo $result ; ?>');
How will I get the output as
MFG_NAME[0] = ABC;
MFG_NAME[1] = XYZ;
DATE[0] = [01-MAR-14,01-APR-14,01-MAY-14];
DATE[1] = [01-MAR-14,01-APR-14,01-MAY-14];
MKT[0] = [0.59,0.25,0.10];
MKT[1] = [0.87,0.67,0.03];
Loop through data, building your arrays. First check to see if you already have a matching MFG_NAME by using indexOf(). If you have a match, use that index for the other arrays. Otherwise create new entries for each variable.
var data = [
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-MAR-14|0.59" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-MAR-14|0.87" },
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-APR-14|0.25" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-APR-14|0.67" },
{ MFG_NAME: "ABC", CONCATED_MKT_SHARE: "01-MAY-14|0.10" },
{ MFG_NAME: "XYZ", CONCATED_MKT_SHARE: "01-MAY-14|0.03" }
];
var MFG_NAME = [];
var DATE = [];
var MKT = [];
data.forEach(function(item) {
var parts = item.CONCATED_MKT_SHARE.split("|");
var i = MFG_NAME.indexOf(item.MFG_NAME);
if (i == -1) {
MFG_NAME.push(item.MFG_NAME);
DATE.push([parts.shift()]);
MKT.push([+parts.shift()]);
}
else {
DATE[i].push(parts.shift());
MKT[i].push(+parts.shift());
}
});
var success = MFG_NAME[0] == "ABC" &&
MFG_NAME[1] == "XYZ" &&
DATE[0].join(",") == "01-MAR-14,01-APR-14,01-MAY-14" &&
DATE[1].join(",") == "01-MAR-14,01-APR-14,01-MAY-14" &&
MKT[0].join(",") == "0.59,0.25,0.1" &&
MKT[1].join(",") == "0.87,0.67,0.03";
document.write(success);
This requires your data to be sorted by date. Your sample data is already sorted by date then name. This will still work if it's sorted by name then date, or if it's sorted by only date, not considering name at all. But, If it's not sorted by date at all, you'll need to do an extra step to sort first (which would be inefficient), or adjust the code to sort as you process the data.
$result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}];';
var_dump(json_decode($result, true));
Maybe it's your solution?!
I guess this is what you want:
var $result = '[{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}]';
var data = new Array();
data = JSON.parse($result);
var MFG_NAME = new Array();
var DATE = new Array();
var MKT = new Array();
var i = 0;
$.each( data, function( key, value ) {
MFG_NAME[i] = value.MFG_NAME;
var MKT_SHARE = value['CONCATED_MKT_SHARE'].split('|');
DATE[i] = MKT_SHARE[0];
MKT[i] = MKT_SHARE[1];
i++;
});
console.log(MFG_NAME[0]);
console.log(MFG_NAME[1]);
console.log(MFG_NAME);
console.log(DATE);
console.log(MKT);
Demo: http://jsfiddle.net/1n51kwze/
var MFG_NAME = [];
var DATE = [];
var MKT = [];
//For each data entry
for(i = 0; i < data.length; i++){
concatString = data[i]["CONCATED_MKT_SHARE"].split("|");
//If name not exists create date and mkt object for name instance
if(MFG_NAME.indexOf(data[i]["MFG_NAME"]) == -1){
MFG_NAME[i] = data[i]["MFG_NAME"];
DATE[i] = [];
MKT[i] = [];
DATE[i].push(concatString[0]);
MKT[i].push(concatString[1]);
}else{
//Else just add to existing
DATE[MFG_NAME.indexOf(data[i]["MFG_NAME"])].push(concatString[0]);
MKT[MFG_NAME.indexOf(data[i]["MFG_NAME"])].push(concatString[1]);
}
}
console.log(MFG_NAME[0]);
console.log(MFG_NAME[1]);
console.log(DATE[0]);
console.log(DATE[1]);
console.log(MKT[0]);
console.log(MKT[1]);
Result looks like this:
ABC
XYZ
["01-MAR-14", "01-APR-14", "01-MAY-14"]
["01-MAR-14", "01-APR-14", "01-MAY-14"]
["0.59", "0.25", "0.10"]
["0.87", "0.67", "0.03"]
Hope this helps :)
You could do that like this:
var data = [{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAR-14|0.59"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAR-14|0.87"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-APR-14|0.25"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-APR-14|0.67"},{"MFG_NAME":"ABC","CONCATED_MKT_SHARE":"01-MAY-14|0.10"},{"MFG_NAME":"XYZ","CONCATED_MKT_SHARE":"01-MAY-14|0.03"}];
var MFG_NAME = [],
DATE = [],
MKT = [];
for(var i = 0; i < data.length; i++){
MFG_NAME.push(data[i].MFG_NAME);
var split = data[i].CONCATED_MKT_SHARE.split("|");
DATE.push(split[0]);
MKT.push(split[1]);
}
alert("MFG_NAME:\n" + JSON.stringify(MFG_NAME) + "\n\n" +
"DATE:\n" + JSON.stringify(DATE) + "\n\n" +
"MKT:\n" + JSON.stringify(MKT));
As you can see, this will result in 3 new arrays containing your data, separated by key.
Oh, and you don't need to declare data before adding properties to it. This'll work just fine:
var data = JSON.parse('<?php echo $result ; ?>');
Related
Plugin: eonasdan/Bootstrap 3 Datepicker
Explaination:
I want to write an application that user can select 5 different hours for each day. so i created an array and add each day (without duplicate), for example user select 31/12/2017 and 30/12/2017 , now i want to give they this ability to select only 5 different hour for each day that selected.
Tried Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
dateArray[unqdate] = unqtime
}
}
console.log(dateArray);
});
JSFiddle
(For testing, select a date, then click on save button, then check console)
Goal:
var dateArray = {
"31-12-2017": [{
"time": "14:00"
}, {
"time": "17:15"
}],
"30-12-2017": [{
"time": "13:00"
}, {
"time": "12:15"
}]
}
Problem:
I couldn't figured out how can i add another time to each day. it's my first time i work with array and object like this.
I want to prevent duplicate entry and only five different hour per day.
Somehow I'm in learning.
There is some problem with your JS Code:
var limit = 5;
var i = 0;
var dateArray = new Object();
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
if ($.inArray(unqdate, dateArray) == -1) {
if(dateArray[unqdate] && dateArray[unqdate].length < limit) {
if(!dateArray[unqdate].find((ele) =>ele.time === unqtime)){
dateArray[unqdate].push({"time": unqtime})
}
} else {
dateArray[unqdate] = [{"time": unqtime}]
}
}
}
console.log(dateArray);
});
Note included logic for time split. You can use split by : and take the first 2 element of array.
I have created JSON response for your requirement.
Result :: JSON.stringify(parentObject)
Code is as below.
$(document).ready(function() {
$('#datetimepicker1').datetimepicker({
stepping: 30,
sideBySide: true,
showTodayButton: true,
format: 'DD-MM-YYYY HH:mm:ss',
});
// my code
var limit = 5;
var i = 0;
var parentObject = new Object();
var parentArray = [];
var dateAndTimeObject;
function isDateSelectedExists(date) {
for (var i = 0; i < parentArray.length; i++) {
var obj = parentArray[i];
if (obj["date"] === date) {
return i;
}
}
return -1;
}
$('#ss').click(function() {
if ($('#datetimepicker1 input').val().length > 0) {
var date = $('#datetimepicker1 input').val();
var getDate = date.split(' ');
var unqdate = getDate[0];
var unqtime = getDate[1];
var tempIndex = isDateSelectedExists(unqdate);
console.log("tempIndex :: " + tempIndex);
if (tempIndex == -1) {
console.log("date doesn't exists");
dateAndTimeObject = new Object();
dateAndTimeObject["date"] = unqdate;
var timeArray = [];
timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
parentArray.push(dateAndTimeObject);
parentObject["res"] = parentArray;
} else {
console.log("date exists");
dateAndTimeObject = parentArray[tempIndex];
var timeArray = dateAndTimeObject["time"];
if(timeArray.length<5) timeArray.push(unqtime);
dateAndTimeObject["time"] = timeArray;
}
console.log("final res :: " + JSON.stringify(parentObject));
}
});});
I have this google spreadsheet script that pulls in json formatted book data. I have no problem displaying book title and author, but he "offerData" object can contain a different amount of elements (prices from sellers) depending on the book. Right now I created a loop and am storing the offerData values like so:
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
and am returning the data like this:
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
Obviously this only returns 3 sellers with price, condition, seller info. The issue is that a book doesn't always have 3 sellers, it can be anywhere from 1 to 10 or so.
My question is how can I return all offerData (price/condition/seller) here? :
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
--
function getBookDetails(isbn) {
// Query the book database by ISBN code.
if (isbn !== "") {
var url = "https://api.bol.com/catalog/v4/search/?apikey=myapi6&offers=all&format=json&q=" + isbn;
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response);
if (results.totalResultSize) {
// There'll be only 1 book per ISBN
var book = results.products[0];
// get Title and Authors
var title = (results.products[0]["title"]);
var specstag = (results.products[0]["specsTag"]);
var offerdata = results.products[0]["offerData"];
if (typeof offerdata.offers !== 'undefined' && offerdata.offers.length > 0) {
var arrayLength = offerdata.offers.length;
var price = [];
var condition = [];
var seller = [];
for (var i = 0; i < arrayLength; i++) {
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
}
}
}
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
return resultRow;
}
}
the answer
var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
resultRow[0][3*i+2]=price[i];
resultRow[0][3*i+3]=condition[i];
resultRow[0][3*i+4]=seller[i];
}
how you should think about it is to see the index of the elements in the array and then find relation between i and the index you want
var resultRow = [
[
title, //[0][0]
specstag, //[0][1]
price[0], //[0][2]
condition[0], //[0][3]
seller[0], //[0][4]
price[1], //[0][5]
condition[1], //[0][6]
seller[1], //[0][7]
price[2], //[0][8]
condition[2], //[0][9]
seller[2]//[0][10]
]
];
You might be looking for something like this;
var data = { title: null,
spcstag: null,
pcs: [],
};
offerData.offers.forEach( p => { var pcsData = {};
!!data.title || data.title = p.title;
!!data.specstag || data.specstag = p.specstag;
pcsData.price = p.price;
pcsData.condition = p.condition;
pcsData.seller = p.seller;
data.pcs.push(pcsData);
});
I have these following arrays
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1','platform-a2','platform-a3'];
var platform_b = ['platform-b1','platform-b2','platform-b3'];
var platform_c = ['platform-c1','platform-c2','platform-c3'];
And I want to convert them into a json which should look like this
{
"Guitar":["platform-a1","platform-a2","platform-a3"],
"Bass":["platform-b1","platform-b2","platform-b3"],
"Amp":["platform-c1","platform-c2","platform-c3"]
}
How would I do this? I would have to do this in pure javascript
Let's present three different approaches to your case:
First one
If you want just to create the json object with your data try:
http://jsfiddle.net/csdtesting/tap2xom9/
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var category = ['Guitar', 'Bass', 'Amps'];
var obj = {
Guitar: platform_a,
Bass: platform_b,
Amps: platform_c
};
document.write(JSON.stringify(obj));
Second
If you want to create it dynamically do something like that:
http://jsfiddle.net/csdtesting/tap2xom9/
var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var FinalObject = {};
FinalObject[category[0]] = platform_a;
FinalObject[category[1]] = platform_b;
FinalObject[category[2]] = platform_c;
document.write(JSON.stringify(FinalObject));
Finally
If you want to be more dynamic then try this :
http://jsfiddle.net/csdtesting/kqwz72os/
var FinalObject = {};
var category = ['Guitar', 'Bass', 'Amps'];
var platforms = {
platform_a: ['platform-a1', 'platform-a2', 'platform-a3'],
platform_b: ['platform-b1', 'platform-b2', 'platform-b3'],
platform_c: ['platform-c1', 'platform-c2', 'platform-c3']
};
for (var i = 0; i < category.length; i++) {
FinalObject[category[i]] = platforms[Object.keys(platforms)[i]];
}
document.write(JSON.stringify(FinalObject));
Hope this helps!
There's no reasonable shortcut here. You just have to do it manually:
var jsonString = JSON.stringify({
"Guitar": platform_a,
"Base": platform_b,
"Amp": platform_c
});
I'm a beginner in java script a trying a little program that parse data from a text file. In order to create a filter on a particular date i have made a function to get the date from and to that the user have enter. And the date a have to compare if it is in the range is in the text file, this date also i got it. But now i don't want to re-write the function "getAllFilesFromFolder" found in the code below, this function must be executed in all case but if i click on the button filter by by date it must read on the files with the date in range given by the user. Can someone give me an explanation on how to do it. i have tried the code below.
function getdate(){
var dateStart = new Date($('#dateStart').val()).getTime();
var dateEnd = new Date($('#dateEnd').val()).getTime();
//if(!testDate){var testDate = new Date(2014, 05, 02).getTime();}
var testDate = new Date(2014, 05, 02).getTime();
if (dateStart <= testDate && testDate <= dateEnd) {
alert('IN');
//Here filter the files with the date
}else{
alert('OUT');
//Here no new to read and parse the file beacause it is out of range
}
}
//Parse folder and file to get the required files
function getAllFilesFromFolder(folder){
//Parsing the given folder the result which is return is kept in an array
var test = fse.readdirSync(folder);
//Going through the array
for(var n=0; test[n]; n++){
var stats = fs.lstatSync(folder+"\\"+test[n]);
if(stats && stats.isDirectory()){
getAllFilesFromFolder(folder+"\\"+test[n]);
var path = folder+"\\"+test[n]+"<br />";
}else{
var path = folder+"\\"+test[n];
//Regex on the file to be taken
var pattern = /^(PM)[0-9]{5}[_](xam)[_](pmbok5th)[_](pmp)[_](v92)(.txt)$/;
var parent = folder+"\\";
var file = test[n];
var load = pattern.test(file);
//Split on file to get the "id user"
identifiant = file.split('_');
//Test the regex on file name "PM*_xam_pmbok5th_pmp_v92.txt"
if(load == true){
var read = fse.readFileSync(path, 'utf8');
var suspendDate = read.lastIndexOf('xam/');
var wantedDate = read.slice(suspendDate);
info = wantedDate.split('/');
var suspendData = read.lastIndexOf('/DB');
var suspendData = wantedDate.lastIndexOf('/DB');
var wantedData = wantedDate.slice(suspendData);
var db_response = wantedData.split(".");
var all_response = db_response[0].split(":");
if(typeof(info[2]) != "undefined" && all_response != "undefined"){
var response = all_response[1].split("|");
//Parsing the array response to find the "id" here id of the question and the "ans" here answer of the question "R" or "W"
for(var p = 0; p < response.length; p++){
//Test if result exist we increment if not it is generate with the function initResp
if(typeof(response[p]) != "undefined"){
var id = response[p].slice(0,6);
var ans = response[p].slice(-1);
if (question[id]) {
question[id][ans] += 1;
} else {
var results = initResp(ans);
question[id] = results;
};
} else {
}
}
} else {
//$("#results1").append("<strong>La session est vide</strong><br>");
}
i++;
}
}
}
};
I found a solution to my problem. See the code below for more information
function rangeDate(testDate){
var dateStart = new Date($('#dateStart').val()).getTime();
var dateEnd = new Date($('#dateEnd').val()).getTime();
if (dateStart <= testDate && testDate <= dateEnd) {
date = true;
return date;
}else{
date = false;
return date;
}
}
function getAllFilesFromFolder(folder)/*, useDate*/{
//Parsing the given folder the result which is return is kept in an array
var test = fse.readdirSync(folder);
//Going through the array
for(var n=0; test[n]; n++){
var stats = fs.lstatSync(folder+"\\"+test[n]);
if(stats && stats.isDirectory()){
getAllFilesFromFolder(folder+"\\"+test[n]);
var path = folder+"\\"+test[n]+"<br />";
}else{
var path = folder+"\\"+test[n];
//Regex on the file to be taken
var pattern = /^(PM)[0-9]{5}[_](xam)[_](pmbok5th)[_](pmp)[_](v92)(.txt)$/;
var parent = folder+"\\";
var file = test[n];
var load = pattern.test(file);
//Split on file to get the "id user"
identifiant = file.split('_');
//Test the regex on file name "PM*_xam_pmbok5th_pmp_v92.txt"
if(load == true){
var read = fse.readFileSync(path, 'utf8');
var suspendDate = read.lastIndexOf('xam/');
var wantedDate = read.slice(suspendDate);
var info = wantedDate.split('/');
testDate = new Date(info[4]).getTime();
rangeDate(testDate);
if(date == true){
var suspendData = read.lastIndexOf('/DB');
var suspendData = wantedDate.lastIndexOf('/DB');
var wantedData = wantedDate.slice(suspendData);
var db_response = wantedData.split(".");
var all_response = db_response[0].split(":");
if(typeof(info[2]) != "undefined" && all_response != "undefined"){
var response = all_response[1].split("|");
//Parsing the array response to find the "id" here id of the question and the "ans" here answer of the question "R" or "W"
for(var p = 0; p < response.length; p++){
//Test if result exist we increment if not it is generate with the function initResp
if(typeof(response[p]) != "undefined"){
var id = response[p].slice(0,6);
var ans = response[p].slice(-1);
if (question[id]) {
question[id][ans] += 1;
} else {
var results = initResp(ans);
question[id] = results;
};
} else {
}
}
} else {
//$("#results1").append("<strong>La session est vide</strong><br>");
}
i++;
}else{
}
}
}
}
};
I'm trying to send some data in an Array via AJAX to save it to the database, I build the array this way:
$( "#saveordering" ).button().click(function( event ) {
event.preventDefault();
var data = document.getElementById('tabs');
var categories = data.getElementsByTagName("div");
var categoryArray = new Array();
for (var i=0; i < categories.length; i++) { //Loop door de categoriƫen
var category = categories[i];
var categoryId = category.getAttribute('id');
categoryArray[i] = new Array();
categoryArray[i]['id'] = categoryId;
categoryArray[i]['forums'] = new Array();
var forums = category.getElementsByTagName("li");
for (var j=0; j < forums.length; j++) { //Loop door de forums
var forum = forums[j];
var forumId = forum.getAttribute('id');
categoryArray[i]['forums'][j] = new Array();
categoryArray[i]['forums'][j]['id'] = forumId;
}
}
$.ajax({
type: 'POST',
url: "ajax/updateboardorder.php",
dataType: 'json',
data: {ldelim}"categories" : categoryArray{rdelim} ,
success: function(data) {
}
});
});
But nothing is send, when I do a var_dump($_POST) in PHP I'm getting:
array (size=0) empty
What am I doing wrong?
Look at this code
categoryArray[i] = new Array();
categoryArray[i]['id'] = categoryId;
categoryArray[i]['forums'**strong text**
Um, that is not an "array", you are making an associative array
categoryArray[i] = {};
categoryArray[i]['id'] = categoryId;
categoryArray[i]['forums'] = {};
or
categoryArray[i] = {
"id" : categoryId,
"forums" : {}
};
You want an object. Same where you do it later in the code with forums.
This is what's going on to your array:
var a = new Array();
a['id'] = 123;
JSON.stringify(a); // []
a; // []
a.length; // 0
a.id; // 123
You are trying to use the array like a primitive object:
var o = {};
o.id = 123;
JSON.stringify(o); // {"id":123}