Generate a Required File using JavaScript - javascript

I need to generate a JSON file using a JAVA script , but am not getting the expected output , can you help me generating out put of this .
Expected out put :
{
"ewh5yuwe": {
"NumCopies": "1",
"NumPages": "10",
"Status": "done printing",
"Title": "demo.jpg",
"Username": "keshavka",
"date": "23:06 Feb 5, 15",
"print status": "OK",
"time": "1429036296",
"timestamp done printing": "${__time(yyyyMMddHMS)"
}
}
out put received after calling print(); function is as below:
""rYajbQx":{[object Object]}"
code:
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 7; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
//above Code is to generate a Random variable
function test() {
var jobid = Math.random();
var jobkey = jobid;
var time = new Date().getTime()
var kes = makeid()
var joblog = {
"NumCopies": "1",
"Status": "done printing",
"Title": "demo.jpg",
"Username": "keshavka",
"date": "23:06 Feb 5, 15",
"print status": "OK",
"time": "1429036296",
"timestamp done printing": time
};
json = JSON.stringify(joblog);
console.log(joblog);
return joblog;
}
// Above code is to generate JSON
var x = test();
console.log(x);
var y = makeid();
console.log(y);
function print() {
a = ('{' + (test()) + '}');
return a;
}

The problem is that you're not returning the JSON, but the object itself.
function test() {
[...]
var json = JSON.stringify(joblog);
console.log(json);
return json;
}

Ok, I think I know what you want. You want to return an object that has a property on it with the name of the id you generate and its value set to the properties listed in the code above. The main thing I would change is how the object is created. So in your test function I would make the following changes:
var joblog = {};
joblog[kes] = {
"NumCopies":"1",
"Status": "done printing",
"Title": "demo.jpg",
"Username": "keshavka",
"date": "23:06 Feb 5, 15",
"print status": "OK",
"time": "1429036296",
"timestamp done printing": time
};
So if you generate an id of '5YhDv7n', you would get an object of type:
{
5YhDv7n:{
ObjectNumCopies: "1",
Status: "done printing",
Title: "demo.jpg",
Username: "keshavka",
date: "23:06 Feb 5, 15",
print status: "OK",
time: "1429036296",
timestamp done printing: 1435580266234
}
}
I edited the JSFiddle I made to reflect these changes.

Related

Print the same child nodes from an object but two levels deep

I'm trying to create a piece of JavaScript that can read through specific parts of a linked object and place them iteratively into another piece of code which then places the code into HTML and into the front-end.
I've managed to get the fetch part working whereby it pulls in the JSON and can be read in the console, when summoned. Once the code runs, I'm able to refer to the data and bring out the whole dataset with something like:
console.log(AllOffers);
and I can drill down into something like the offerName in the JSON by using the following syntax in a variable and calling it in the console:
var OfferName = data.offersBreakdown.allOffers[0].offers[0].offerName;
However this only pulls in the first iteration of offerName because in the variable I've set it to look into the first iteration of its parent, 'offers'. What I'm looking to do is create a variable which prints all of the offerName data so that I can call on it instead of the data_test variable further down in the code, which processes the data into HTML. Sounds confusing? It is.
Ideally what I think I need is to be able to ask it to look into each child item of 'offers' (rather than just the first one) and then have it look for 'offerName'. I can't work out how one would achieve this. The best I can come up with is to remove the [0] from 'offers', but if I do that, it returns undefined as the result.
Here's my JavaScript (and a bit of jQuery):
<script>
// fetch call for the JSON data (see below)
fetch('api_url', {
headers: {
'Authorization': 'auth_token'
}
})
.then(response => response.json())
.then(function (data) {
var AllOffers = data.offersBreakdown.allOffers[0];
var AllOffers_Offers = data.offersBreakdown.allOffers[0].offers;
var OfferName = data.offersBreakdown.allOffers[0].offers[0].offerName;
var OfferImageUrl = data.offersBreakdown.allOffers[0].offers[0].imageUrl;
console.log(AllOffers);
function createCard(cardData) {
var cardTemplate = [
'<div class="card">',
'<p>My name is: ',
cardData.Offer || 'No offer',
'</p>',
'<p>My job is: ',
cardData.Img || 'No image',
'</p></div>'
];
// a jQuery node
return jQuery(cardTemplate.join(''));
}
var data_test = [
{ "Name": OfferName, "Img": OfferImageUrl },
{ "Name": OfferName, "Img": OfferImageUrl },
{ "Name": OfferName, "Img": OfferImageUrl },
];
var cards = jQuery();
// Store all the card nodes
data_test.forEach(function(item, i) {
cards = cards.add(createCard(item));
});
// Add them to the page... for instance the <body>
jQuery(function() {
jQuery('body').append(cards);
});
</script>
Here's the JSON
<script>
// the JSON
{
"offersBreakdown": {
"totalAddedOffers": 0,
"totalOffers": 2,
"totalAddedRewards": 0,
"totalRewards": 0,
"totalAddedStreakOffers": 0,
"totalStreakOffers": 0,
"allOffers": [
{
"offers": [
{
"offerName": "Offer name 1",
"imageUrl": "https://url_path_1.jpg"
},
{
"offerName": "Offer name 2",
"imageUrl": "https://url_path_2.jpg"
},
{
"offerName": "Offer name 3",
"imageUrl": "https://url_path_3.jpg"
},
{
"offerName": "Offer name 4",
"imageUrl": "https://url_path_4.jpg"
}
]
}
</script>
I'm assuming what you're looking for is a way to loop through all of the offerNames, in which case a simple for loop would suffice. Since your data includes nested arrays and objects, we need two loops, one to iterate through your allOffers array and then a nested for loops to iterate through the offers array inside of your allOffers array
var data = {
"offersBreakdown": {
"totalAddedOffers": 0,
"totalOffers": 2,
"totalAddedRewards": 0,
"totalRewards": 0,
"totalAddedStreakOffers": 0,
"totalStreakOffers": 0,
"allOffers": [{
"offers": [{
"offerName": "Offer name 1",
"imageUrl": "https://url_path_1.jpg"
}, {
"offerName": "Offer name 2",
"imageUrl": "https://url_path_2.jpg"
}, {
"offerName": "Offer name 3",
"imageUrl": "https://url_path_3.jpg"
}, {
"offerName": "Offer name 4",
"imageUrl": "https://url_path_4.jpg"
}]
}]
}
};
var allOffers = [];
var jsonObjectAllOffers = data.offersBreakdown.allOffers;
for (var i = 0; i < jsonObjectAllOffers.length; i++) {
var offers = jsonObjectAllOffers[i].offers;
for (var j = 0; j < offers.length; j++) {
var objectToAppend = {
"Name": offers[j]["offerName"],
"Img": offers[j]["imageUrl"]
};
allOffers.push(objectToAppend);
}
}
console.log(allOffers);
And now you can use your allOffers variable to loop through with the "forEach" and make into HTML

How to transform object to nested object

I am new in JavaScript and programming. I get data via AJAX. I want to re-generate it to get a nested object grouped by part of the data. In this case I want it grouped by year and month
Here is my data and my function:
myObj = [
{"date":'2019-06-05',"name":"abc 0"},
{"date":'2019-06-01',"name":"abc 1"},
{"date":'2019-05-25',"name":"abc 2"},
{"date":'2019-05-15',"name":"abc 3"},
{"date":'2020-06-30',"name":"abc 4"},
{"date":'2020-06-25',"name":"abc 5"},
{"date":'2020-05-28',"name":"abc 6"},
{"date":'2020-05-26',"name":"abc 7"}
];
function regenerate(data) {
var result = {
"allyears": [{}]
};
for (x = 0; x < data.length; x++) {
var year = data[x].date.slice(0, 4);
var month = data[x].date.slice(5, 7);
if (!result.allyears.months) {
result.allyears['year'] = year;
result.allyears.months = [{}];
}
if (!result.allyears.months.data) {
result.allyears.months['month'] = month;
result.allyears.months.data = [{}];
}
result.allyears.months.data[x] = data[x];
}
console.log(result);
return result;
};
regenerate(myObj);
Result I expect:
{
"allyears": [{
"year": "2019",
"months": [{
"month": "06",
"data": [{
"date": '2019-06-05',
"name": "abc 0"
},
{
"date": '2019-06-01',
"name": "abc 1"
}
]
}, {
"month": "05",
"data": [{
"date": '2019-05-25',
"name": "abc 2"
},
{
"date": '2019-05-15',
"name": "abc 3"
},
]
}]
}]
};
What am I missing in my function?
Probably not the cleverest solution, but it should do the job "beautifully".
The routine is taking the advantage of Array.reduce, where an initial accumulator (in this case an empty array) is used and, while looping the original myObj array, it checks whether:
The year element exists in the array. If it doesn't it creates it.
The month element exists in the year element. If it doesn't it creates it.
Once everything is created, it adds data to the current month.
I will add some comments to the snippet below for further explanations, the output, to me, seems okay.
const myObj = [
{"date":'2019-06-05',"name":"abc 0"},
{"date":'2019-06-01',"name":"abc 1"},
{"date":'2019-05-25',"name":"abc 2"},
{"date":'2019-05-15',"name":"abc 3"},
{"date":'2020-06-30',"name":"abc 4"},
{"date":'2020-06-25',"name":"abc 5"},
{"date":'2020-05-28',"name":"abc 6"},
{"date":'2020-05-26',"name":"abc 7"}
];
let res = {
allyears: myObj.reduce((acc, next) => {
let [year, month, day] = next.date.split('-');
// ^-- Acquire year, month and day (actually, day is not needed) from the original date string.
let yearRef = acc.find(i => i.year === year);
// ^-- checks whether the current year already exists in the array.
if (!yearRef) acc.push({year}), yearRef = acc[acc.length - 1];
// ^-- if it doesn't, it creates it and fill the above reference of it.
yearRef.months = yearRef.months || [];
// ^-- same as the year above, but with month.
let monthRef = yearRef.months.find(i => i.month === month);
if (!monthRef) yearRef.months.push({month}), monthRef = yearRef.months[yearRef.months.length - 1]// ^-- same as above, with month.
monthRef.data = (monthRef.data || []).concat(next);
// ^-- once the month element is available, add the next element to data. If data does not yet exist, init it.
return acc;
}, [])
};
console.log(res);

how to add filter for json data

I am having many such entries in my json data. The "type" consists of tw attributes i.e. income and expense. How to print the "label" which have type="expense" in using JavaScript.
This json data below is just an example.
Check the image to get a better idea of json data.
"expenses_veterinary":{
label:"Veterinary, breeding, and medicine"
name:"expenses_veterinary"
total:0
type:"expense"
}
console.log($ctrl.gold_standard_categories); prints all the json data.
I tried the code written below but its not working.
if($ctrl.gold_standard_categories.name.type=expense){
console.log($ctrl.gold_standard_categories.label);
}
It prints all the data because of the single equals sign in your if statement.
It means you are always trying to assign the value "expense" to your type property and so the if statement will always evaluate to true.
What you are intending to do is compare the values, not assign a value.
https://jsfiddle.net/yxL4rpj2/
assume that in var money you store the json response
var grouppedMoney = {
expenses: [],
incomes: []
};
for(var i = 0; i <= money.length - 1; i++){
for(moneyType in money[i]){
var _typeString = money[i][moneyType].type == 'expense' ? 'expenses' : 'incomes';
grouppedMoney[_typeString].push(money[i][moneyType]);
}
}
Here is the basic example.Iterate over your object and see type value is equal to expense then print the label value.
var data = {
"expenses_veterinary":{
"label":"Veterinary, breeding, and medicine",
"name":"expenses_veterinary",
"total":0,
"type":"income"
},
"expenses_car":{
"label":"bus and truck",
"name":"expenses_car",
"total":0,
"type":"expense"
}
};
for (var property in data) {
if (data.hasOwnProperty(property)) {
// do stuff
if(data[property]['type']=='expense'){
console.log(data[property]['label']);
}
}
}
It seems you are using AngularJS ($ctrl) so you may consider using either native angular filters or custom filter to do this.
BTW, using vanilla JS, this simple loop will work :
for(var key in jsonData) {
if("expense" === jsonData[key]["type"]) {
console.log(jsonData[key]["label"]);
}
}
Sample snippet
var jsonData = {
"expensesigoods": {
"name": "expenses_goods",
"label": "Cost of goods sold",
"type": "expense",
"total": 0
},
"expensesicar": {
"name": "expenses_car",
"label": "Car and truck expenses",
"type": "expense",
"total": 0
},
"expensesichemicals": {
"name": "expenses_chemicals",
"label": "Chemicals",
"type": "expense",
"total": 0
},
"expensesiconservation": {
"name": "expenses_conservation",
"label": "Conservation expenses",
"type": "other",
"total": 0
}
}
for(var key in jsonData) {
if("expense" === jsonData[key]["type"]) {
console.log(jsonData[key]["label"]);
}
}
Try Array.filter() method to filter the data based on type="expense".
Working Fiddle
var obj = {
"expenses_goods":{
"label":"expenses_goods",
"name":"expenses goods",
"total":0,
"type":"income"
},
"expenses_cars":{
"label":"expenses_cars",
"name":"expenses cars",
"total":0,
"type":"expense"
},
"expenses_veterinary":{
"label":"expenses_veterinary",
"name":"expenses veterinary",
"total":0,
"type":"income"
}
};
var res = Object.keys(obj).filter(item => { return obj[item].type == 'expense' });
for (var i in res) {
document.getElementById("result").innerHTML = obj[res[i]].label;
}
<div id="result">
</div>

Replace JSON Object Programmatically

I'm looking for the most effective way to replace a JSON Object in a file.
20150628 - Update at the bottom of this post
Here's the scenario:
I have a bunch of JSON files (many) and in these files are large chunks of JSON (sometimes 20-30K lines of it). These are configurations for various testing routines we have. Recently, a change was required to change an object from this:
"createdAt": {
"year": 2014,
"month": 11,
"dayOfMonth": 24,
"hourOfDay": 2,
"minute": 22,
"second": 54
}
to a format like this:
"createdAt":"2015-05-12T21:14:51Z"
Let's even make this easier. I want to replace all of the createdAt and updatedAt fields in my JSON object (which there can be many) with:
"createdAt":"2015-05-12T21:14:51Z"
or
"updatedAt":"2015-05-12T21:14:51Z"
There are NUMEROUS (100's of these) objects in each file, with different values for the fields. I need to go through and replace every createdAt and updatedAt object with the new format. The date's do not matter. I can have them be anything.
I can do this by hand, but it will literally take me a day or two to do of full time work (I know, I tried to do one file and after 1/2 hour I gave up, it was taking way too long).
How can I do this programmatically?
Regex? Sed? Something else?
Final note: I only need to do this once. After that, I won't need to do it again.
Thanks for any tips!
Example JSON: (Just imagine the real one is 30,000 lines!) :)
{ "products": [
{
"displayOrder": 3,
"product": {
"foo": "bar",
"createdAt": {
"year": 2014,
"month": 11,
"dayOfMonth": 24,
"hourOfDay": 2,
"minute": 22,
"second": 54
},
"description": "Fizz Bin",
"id": "8765309",
"modelNumber": "call-it",
"name": "Boom",
"price": {
"amount": 100,
"currency": "USD"
},
"type": "Active",
"updatedAt": {
"year": 2015,
"month": 1,
"dayOfMonth": 27,
"hourOfDay": 19,
"minute": 33,
"second": 25
}
}
},
{
"displayOrder": 4,
"product": {
"foo": "barx",
"createdAt": {
"year": 2013,
"month": 1,
"dayOfMonth": 4,
"hourOfDay": 3,
"minute": 2,
"second": 5
},
"description": "Fizzy Stuff",
"id": "876511111",
"modelNumber": "zoom-zoom-1000",
"name": "Zoom Zoom 1000",
"price": {
"amount": 1000,
"currency": "USD"
},
"type": "Active",
"updatedAt": {
"year": 2011,
"month": 5,
"dayOfMonth": 25,
"hourOfDay": 15,
"minute": 35,
"second": 55
}
}
}
]
}
UPDATE 20150628
For those wondering, here's the gulpfile I wrote to accomplish exactly what I wanted. It is based off of the accepted answer. It will recursively search the tree for what I'm looking for an replace it when found. Its not the prettiest thing in the world, but it did exactly what I needed and saved me a couple weeks of manual time. Total time to process all my files? Under 100ms. Amazing.
var gulp = require('gulp');
var change = require('gulp-change');
function searchTreeForDates(obj) {
if(typeof(obj) === 'object') {
for (var key in obj) {
if (typeof(obj[key]) === 'object' && (key === 'createdAt' || key === 'updatedAt')) {
obj[key] = "2015-06-29T00:53:00Z";
} else {
obj[key] = searchTreeForDates(obj[key])
}
}
}
return obj;
}
function updateDate(content) {
var obj = JSON.parse(content);
obj = searchTreeForDates(obj);
return JSON.stringify(obj);
}
gulp.task('change', function() {
return gulp.src('*.json')
.pipe(change(updateDate))
.pipe(gulp.dest('changed/'))
});
Here is an initial stab. You implement your own "date parsing logic." It requires you to install gulp. And save this in a gulpfile.js . You would need to possibly loop over all the properties that are "date" objects. But that logic isn't that hard.
var gulp = require('gulp');
var change = require('change');
function translateDate(dateField){
return dateField.A + dateField.b + ...;
}
function updateDate(content) {
var obj = JSON.parse(content);
//loop over the obj properties and call the below
// for the ones you want to change.
obj.dateField = translateDate(obj.dateField);
return JSON.stringify(obj);
}
gulp.task('change', function() {
return gulp.src('**/*.json')
.pipe(change(updateDate))
.pipe(gulp.dest('changed/'))
});
Why not manually?
function formatDate(dateObject){
var formattedDate =
dateObject['year']+'-'+
dateObject['month']+'-'+
dateObject['dayOfMonth']+'T'+
dateObject['hourOfDay']+':'+
dateObject['minute']+':'+
dateObject['second']+'Z';
}
var jsonArray = {...};
for(var key in jsonArray){
for(var i = 0; i < jsonArray[key].length; i++){
jsonArray[key][i]['createdAt'] = formatDate(jsonArray[key]['createdAt']);
jsonArray[key][i]['updatedAt'] = formatDate(jsonArray[key]['updatedAt']);
}
}
Open each file, change the property with a convert function and then save the new JSON:
function changeDate(obj) {
var newObject = obj.year + '-' + obj.month + '-' + obj.dayOfMonth + 'T' + obj.hourOfDay + ':' + obj.minute + ':' + obj.second;
return newObject;
}
// here you open the file and stores it's content in the products variable.
for (var i = 0; i < products.length; i++) {
var product = products[i];
product.product.createdAt = changeDate(product.product.createdAt);
product.product.updatedAt = changeDate(product.product.updatedAt);
}
// .. now you need to save the modified json

Javascript sort function on dates not working

So I have this code -
console.log(data);
data = data.sort(function(d1,d2){
var a1= d1["date"].split('/'), b1=d2["date"].split('/');
if(a1[2]==b1[2]){
return (a1[0]==b1[0])? a1[1]-b1[1]: a1[0]-b1[0];
}
return a1[2]-b1[2];
});
console.log("DATA");
console.log(data);
with this data -
[
{ "date": "2/7/2012", "quantity: " 4"},
{ "date": "2/4/2012", "quantity: "5"},
{ "date": "2/3/2012", "quantity: "10"},
{ "date": "2/5/2012", "quantity" : "12"},
{ "date": "2/6/2012", "quantity" : "10"}
]
The two console logs show the data in the same way, or the sorting has no effect. The data coming out of the sort function is in the same order as the data going in.
Why?
Try:
data = data.sort(function(d1,d2){
return new Date(d1.date) - new Date(d2.date);
});
DD/MM/YYYY should be acceptable by Date parser, here is the spilt version.
data = data.sort(function(d1, d2){
var d1 = d1.split('/'), d2 = d2.split('/');
return new Date(d1[2], d1[0] - 1, d1[1]) - new Date(d2[2], d2[0] - 1, d2[1]);
});

Categories