Converting an array object to another object-Part 2 in javascript - javascript

This is a follow up question of Converting an object into array
.Now I would like to do a reverse engineering where I want to convert back the JOSN to the original format except its a object ,like as shown in the example below.
var data1=[
{
"name": "Coal",
"value": "2",
"time": "2015-11-31 00:00:00",
"level":"10"
},
{
"name": "Shale",
"value": "4",
"time": "2015-10-31 00:00:00",
"level":"20"
}
]
to
var data2=
{
"Coal": {
"September 2015": "2",
"level":"10"
},
"Shale": {
"October 2015": "4",
"level":"20"
}
}
where the result is an object not an array.Can anyone pls help me on this issue

function yymmddToString(yymmdd) {
var months = ['January', 'February', 'March', 'April' .....];
var x = yymmdd.split('-');
return months[parseInt(x[1], 10)] + ' ' + x[0];
}
var result = data1.reduce(function(result, datum) {
var x = result[datum.name] = result[datum.name] || {};
x[yymmddToString(datum.time)] = datum.value;
return result;
}, {});

Related

How can I obtain a new json with only unique values from the original

I'm having a hard time trying to obtain a json that has only unique (date, hour) values from two keys combined. The json is something like this:
{
"date": "2019-07-11",
"hour": "12:00",
"idAppointmentsHour": 47914218,
"shift": "T"
},
So if they have the same date and the same shift, I want to group this info. Im using ES5, and my code so far is like this:
for (var i = 0; i < agendaDatas.length; i++) {
if (!datas.includes(agendaDatas[i].data)) {
if (!datas.includes(agendaDatas[i].turno)) {
datas.push({"date": agendaDatas[i].data});
datas.push({"shift": agendaDatas[i].shift})
}
}
}
I have tried includes
All the values from the json are being copyied. i can't use ES6 Set because the platform runs in ES5.
Basically, you could take an array of keys for a grouping identifier and use an object for grouping same groups.
function getKey(keys) {
return function (object) {
return keys.map(function (k) { return object[k]; }).join('|');
};
}
var getKeyDateShift = getKey(['date', 'shift']),
groups = Object.create(null),
result = data.reduce(function (r, o) {
var key = getKeyDateShift(o);
if (!groups[key]) {
result.push(groups[key] = { date: o.date, shift: o.shift, data: [] });
}
groups[key].data.push(o);
return r;
}, []);
You can do it with a cycle, on each iteration via .filter() check whether a match already exists. If not, then create it. Anyway, add the unique-ish values to the group:
//Test data
var items = [
{
"date": "2019-07-11",
"hour": "12:00",
"idAppointmentsHour": 47914218,
"shift": "T"
}, {
"date": "2019-07-11",
"hour": "12:01",
"idAppointmentsHour": 47914219,
"shift": "T"
}, {
"date": "2019-07-11",
"hour": "12:02",
"idAppointmentsHour": 47914220,
"shift": "T"
}, {
"date": "2019-07-11",
"hour": "12:03",
"idAppointmentsHour": 47914218,
"shift": "TY"
},
];
//The logic
var output = [];
for (var item of items) {
var existent = output.filter(function(current) {
return ((item.date === current.date) && (item.shift === current.shift));
});
existent = (existent.length ? existent[0] : {date: item.date, shift: item.shift, group : []});
if (!existent.group.length) output.push(existent);
existent.group.push({
idAppointmentsHour: item.idAppointmentsHour,
hour: item.hour
});
}

"Cannot set property of undefined error" when trying to convert the data from one format to another

I am trying to convert data from one format to another:
The input format json is as follows:
[
{
"part_number": "12312311",
"part_description": "HELIUM FILLING AND GAS CALIBRATION KIT",
"quantity": "3",
"available_quantity": "0",
"ordered_tool_id": "28",
"tool_id": "15",
"wh_data": [
{
"wh_name": "TI02 - (DHL)",
"wh_id": "3",
"wh_code": "TI02",
"wh_qty": 2
},
{
"wh_name": "TI03 - (Secunderabad WH)",
"wh_id": "4",
"wh_code": "TI03",
"wh_qty": 1
}
],
"tool_order_id": "22"
},
{
"part_number": "90FG34",
"part_description": "LINEARITY PHANTOM KIT",
"quantity": "2",
"available_quantity": "0",
"ordered_tool_id": "29",
"tool_id": "17",
"wh_data": [
{
"wh_name": "TI02 - (DHL)",
"wh_id": "3",
"wh_code": "TI02",
"wh_qty": 1
},
{
"wh_name": "TI03 - (Secunderabad WH)",
"wh_id": "4",
"wh_code": "TI03",
"wh_qty": 1
},
{
"wh_name": "TI06 - (Bangladesh)",
"wh_id": "7",
"wh_code": "TI06",
"wh_qty": 1
}
],
"tool_order_id": "22"
}
]
I have to convert it into this format:
{
"sso_id": "123",
"tool_order_id": "22",
"od_req_qty": {
"28": "3",
"29": "2"
},
"post_od_tool": {
"28": "15",
"29": "17"
},
"post_qty": {
"3": {
"28": "2",
"29": "1"
},
"4": {
"28": "1",
"29": "1"
}
},
"submit_fe": "1"
}
I had written code for the conversion as follows:
convertLogic(data, ssoid) {
var toolOrderId = data[0].tool_order_id;
console.log(toolOrderId);
var values = '{"sso_id":"' + ssoid + '","tool_order_id":"' + toolOrderId + '","od_req_qty":{},"post_od_tool":{},"post_qty":{},"submit_fe":"1"}';
var jsObj = JSON.parse(values);
console.log(jsObj);
var warehouseIds = [];
data.forEach(element => {
var orderToolID = element.ordered_tool_id;
var quantity = element.quantity;
var toolId = element.tool_id;
jsObj.od_req_qty[orderToolID] = quantity;
jsObj.post_od_tool[orderToolID] = toolId;
var warehouses = element.wh_data;
warehouses.forEach(warehouse => {
jsObj.post_qty[warehouse.wh_id] = {};
warehouses.forEach(warehouse => {
jsObj.post_qty[warehouse.wh_id][orderToolID] = warehouse.wh_qty;
});
});
});
}
But it is giving this error :
core.es5.js:1020 ERROR TypeError: Cannot set property '28' of undefined
Can anyone help me and tell me how to do the format conversion. I had wasted my whole day and completely exhausted but able to do the conversion.
Wherever you are using code like object[propertyName] = someValue, you need to make sure that the object is "defined" before. Otherwise it will consider it as undefined and hence the error.
Eg: for this line in your code -
jsObj.od_req_qty[orderToolID] = quantity;
You need to do something like -
jsObj.od_req_qty = jsObj.od_req_qty || {};
jsObj.od_req_qty[orderToolID] = quantity;
Similarly for others as well.
Check the fiddle here. The error disappears in the console.

Javascript code to split JSON data into two datapoints array to bind with stackedbar chart canvasjs?

I have variable data having json data as below:
[
{
"BillingMonth":"11",
"BillingYear":"2016",
"Volume":"72",
"BillingMonthName":"November",
"BillingProduct":"Product1"
},
{
"BillingMonth":"11",
"BillingYear":"2016",
"Volume":"617",
"BillingMonthName":"November",
"BillingProduct":"Product2"
},
{
"BillingMonth":"12",
"BillingYear":"2016",
"Volume":"72",
"BillingMonthName":"December",
"BillingProduct":"Product1"
},
{
"BillingMonth":"12",
"BillingYear":"2016",
"Volume":"72",
"BillingMonthName":"December",
"BillingProduct":"Product2"
}
]
What I want to split above json data using javascript/jquery and get them stored in two variables data1, data2 having json data as below as result:
{
type: "stackedBar",
legendText: "Product1",
showInLegend: "true",
data1: [
{ x: November, y: 72 },
{ x: December, y: 72 },
]
}
and
{
type: "stackedBar",
legendText: "Product2",
showInLegend: "true",
data2: [
{ x: November, y: 617 },
{ x: December, y: 72 },
]
}
The above will bind in canvas js stackedbar chart.
Thanks!
Hey here's a solution I had a lot of fun working on I hope it works well for you. I wasn't sure if you would always have 2 products product1, product2 so I went with a more general approach for n amount of products. The result is in an array format, but you can use es6 destructuring to get the two variables data1 and data2 like I did below:
/*
* helper function to restructure json in the desired format
*/
function format(obj) {
var formatted = {
"type": "stackedBar",
"legendText": obj.BillingProduct,
"showInLegend": "true",
"data": [{
"x": obj.BillingMonthName,
"y": obj.Volume
}]
}
return formatted;
}
/*
* returns an array of unique products with corresponding BillingMonth/Volume data
*/
function getStackedBarData(data) {
// transform each obj in orignal array to desired structure
var formattedData = data.map(format);
// remove duplicate products and aggregate the data fields
var stackedBarData =
formattedData.reduce(function(acc, val){
var getProduct = acc.filter(function(item){
return item.legendText == val.legendText
});
if (getProduct.length != 0) {
getProduct[0].data.push(val.data[0]);
return acc;
}
acc.push(val);
return acc;
}, []);
return stackedBarData;
}
var data = [{
"BillingMonth": "11",
"BillingYear": "2016",
"Volume": "72",
"BillingMonthName": "November",
"BillingProduct": "Product1"
}, {
"BillingMonth": "11",
"BillingYear": "2016",
"Volume": "617",
"BillingMonthName": "November",
"BillingProduct": "Product2"
}, {
"BillingMonth": "12",
"BillingYear": "2016",
"Volume": "72",
"BillingMonthName": "December",
"BillingProduct": "Product1"
}, {
"BillingMonth": "12",
"BillingYear": "2016",
"Volume": "72",
"BillingMonthName": "December",
"BillingProduct": "Product2"
}]
var dataVars = getStackedBarData(data);
var data1 = dataVars[0];
var data2 = dataVars[1];
console.log(data1);
console.log(data2);
Hope this helps you!

Evaluating key values in multi-dimensional object

I have a multi-dimensional object that looks like this:
{
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}
I am trying to evaluate the value of "total" in "links." I can do this in a one-dimensional array, like this:
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (!isNaN(data[i][key])) {
data[i][key] = +data[i][key];
}
}
};
But I have not been able to figure out how to do this in two-dimensions (especially calling the value of key "total" by name).
Can anybody set me on the right track? Thank you!
Starting from the principle that the structure of your array is this, you can to iterate the keys and the values:
var obj = {
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
};
for (var key in obj){
obj[key].forEach(function(item){
for(var subkey in item){
if (subkey == 'total')
console.log(item[subkey]);
};
});
};
You can get total using reduce
check this snippet
var obj = {
"links": [{
"source": "58",
"target": "john",
"total": "95"
}, {
"source": "60",
"target": "mark",
"total": "80"
}, {
"source": "60",
"target": "mark",
"total": "80"
}],
"nodes": [{
"name": "john"
}, {
"name": "mark"
}, {
"name": "rose"
}]
}
var links = obj.links;
var sum = links.map(el => el.total).reduce(function(prev, curr) {
return parseInt(prev, 10) + parseInt(curr, 10);
});
console.log(sum);
Hope it helps
Extract the values from the array, convert them to numbers and add them up.
Array.prototype.map() and Array.prototype.reduce() are pretty helpful here:
var data = {"links":[{"source":"58","target":"john","total":"95"},{"source":"60","target":"mark","total":"80"}], "nodes":[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]};
var sum = data.links.map(function(link) {
return +link.total;
}).reduce(function(a, b) {
return a + b;
});
console.log(sum);

How to loop json array to get key and value in javascript?

I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};

Categories

Resources