How to make program to generate json array? - javascript

I need to have more destinationColumn to fit in current development environment.
For following example, it shows destinationColumn: 3, 4 and 5.
var columnSummary= [
{
ranges: [[16, 19]],
destinationRow: 20,
destinationColumn: 3,
type: 'sum',
forceNumeric: true
},
{
ranges: [[16, 19]],
destinationRow: 20,
destinationColumn: 4,
type: 'sum',
forceNumeric: true
},
{
ranges: [[16, 19]],
destinationRow: 20,
destinationColumn: 5,
type: 'sum',
forceNumeric: true
}
];
How to make program to generate mentioned array? Any help would be appreciated.

Based on
How to create json by javascript for loop?
donohoe's code
<script>
// var status = document.getElementsByID("uniqueID"); // this works too
var status = document.getElementsByName("status")[0];
var jsonArr = [];
for (var i = 0; i < status.options.length; i++) {
jsonArr.push({
id: status.options[i].text,
optionValue: status.options[i].value
});
}
</script>
I figured out the method to solve my own question, as follows:
var columnSummary = [];
for (var i = 3; i <= 12; i++) {
columnSummary.push({
ranges: [[16, 19]],
destinationRow: 20,
destinationColumn: i,
type: 'sum',
forceNumeric: true
});
}

Related

Convert key, values JSON array to tabular JSON format

I have following JSON data for Chart
var chartJson = [
{
header : '2016',
values : [1, 5, 9]
},
{
header : '2017',
values : [2, 4, 8]
},
{
header : '2018',
values : [3, 1, 5]
}
];
And needs to convert it into this format to feed my HTML table
var tableJson = [
{
2016 : 1,
2017 : 2,
2018 : 3
},
{
2016 : 5,
2017 : 4,
2018 : 1
},
{
2016 : 9,
2017 : 8,
2018 : 5
}
];
Any quick help will be appreciated to convert it into this format.
I tried using this code, but somehow missing on the logic.
let table = [];
for(var row of chartJson ){
for(var value of row.values)
{
table.push(
{
column : row.header,
value : value
});
}
}
var chartJson = [{
header: '2016',
values: [1, 5, 9]
},
{
header: '2017',
values: [2, 4, 8]
},
{
header: '2018',
values: [3, 1, 5]
}
];
let table = [];
chartJson.forEach((row, index) => {
row.values.forEach((val, j) => {
table[j] = { ...table[j],
[row.header]: val
}
});
});
console.log(table)
Iterate through every chartJson's element with its' values(through inner loop) till values' length and make an object from that.
Finally, push that object into the table array.
That's it.
Have a look at the snippet below:
var chartJson = [
{
header: '2016',
values: [1, 5, 9]
},
{
header: '2017',
values: [2, 4, 8]
},
{
header: '2018',
values: [3, 1, 5]
}
];
let table = [];
let len_of_chartJson = chartJson.length, len_of_values = chartJson[0].values.length;
for (var i = 0; i < len_of_chartJson; i++) {
let obj = {};
for (var j = 0; j < len_of_values; j++) {
obj[chartJson[j].header] = chartJson[j].values[i];
}
table.push(obj);
}
console.log(table);
let table = chartJson.reduce((tbl, rec) => {
rec.values.forEach((num, index) => {
if(!tbl[index]){
tbl[index] = {}
}
tbl[index][rec.header] = num
})
return tbl
}, [])
Array reduce function is used to loop through each object, than for each object it loop through each value, checking if the index exist in the table, if it does not exist, it create an empty object at current index. Finally it creates a key value in the current index object.
You read more about reduce function below
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

loop returning the same value

I need to replace a template array with values from another array and push it to the final result.
This is what I have tried, the problem is that I get the same value when I loop.
var pickups = [
{ address: "Lusaka, Zambia", distance: 22 },
{ address: "Ndola, Zambia", distance: 44 }
];
var template = [{ lable: "distance", data: 0 }];
var final_templates = [];
var pickup_temp = template;
for (var i = 0; i < pickups.length; i++) {
for (var m = 0; m < template.length; m++) {
if (pickup_temp[m].lable == "distance") {
pickup_temp[m].data = pickups[i].distance;
}
}
final_templates.push(pickup_temp);
}
console.log(final_templates);
Expected Result:
[[{lable: "distance", data: 22}],[{lable: "distance", data: 44}]]
Actual Result (same distance value):
[[{lable: "distance", data: 44}],[{lable: "distance", data: 44}]]
It is simpler if the code avoids for loops and just uses Array.map:
var pickups = [
{ address: "Lusaka, Zambia", distance: 22 },
{ address: "Ndola, Zambia", distance: 44 }
];
var template = [{ lable: "distance", data: 0 }];
var final = pickups.map(pick => (
template.map( item => (
{ label: item.lable, data: pick[item.lable] }
))
));
console.log(JSON.stringify(final));

Convert multiple objects in array into an array

I want to convert this:
var x = [{ order_id: 10,
product_id: 5,
product_after_price: 50 },
{ order_id: 10,
product_id: 6,
product_after_price: 50 }]
Into this:
[[10, 5, 50], [10, 6, 50]]
I tried .map() function but it just doesn't work. Any help would be appreciated, thank you!
If you want to ensure the order of the values in the array across different JS engines, you can create an array of property keys (order), and iterate it to get the values in the requested order.
const order = ['order_id', 'product_id', 'product_after_price'];
const x = [{"order_id":10,"product_id":5,"product_after_price":50},{"order_id":10,"product_id":6,"product_after_price":50}];
const result = x.map((o) => order.map((key) => o[key]));
console.log(result);
Without considering order, simply use map
arr.map( s => Object.values(s) )
But you need to specify the order first
var order = ["order_id", "product_id", "product_after_price"];
then use map
var output = arr.map( function(item){
return order.reduce( function(a,c){
a.push( item[c] );
return a;
}, []);
})
Demo
var order = ["order_id", "product_id", "product_after_price"];
var x = [{
order_id: 10,
product_id: 5,
product_after_price: 50
},
{
order_id: 10,
product_id: 6,
product_after_price: 50
}
];
var output = x.map(function(item) {
return order.reduce(function(a, c) {
a.push( item[c] );
return a;
}, []);
});
console.log(output);
It is really the very simple question, it is my kind advice that you should refer javascript core functions first before post a question here.
var x = [{ order_id: 10,
product_id: 5,
product_after_price: 50 },
{ order_id: 10,
product_id: 6,
product_after_price: 50 }]
var arrValues = []
for(var index=0; index< x.length; index++){
if(!!x[index]){
arrValues.push(Object.values(x[index]));
}
}
console.log(arrValues);

Getting Unique value from an array

So I have 2 arrays like these ...
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"]
var user_count = [3, 3, 3, 3, 7, 20, 94, 142]
I want results like these
var result_browser_names = ["Firefox", "Maxthon", "Opera", "Chrome", "Edge"]
var result_user_count = [145, 3, 6, 27, 94]
As you can see 'result_browser_names' contains unique browser name values &
'result_user_count' contains 'sum of users' for each type of browser.
I have seen this solution, which works great for a single array. In my case I have 2 arrays ....
Any help is very much appreciated. Thanks
I'd suggest using an object. Assuming your 2 arrays will always match in length:
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"]
var user_count = [3, 3, 3, 3, 7, 20, 94, 142]
var lib = {}
for (var i=0; i < browser_names.length; i++) {
if (lib[browser_names[i]] != undefined) {
lib[browser_names[i]] += user_count[i];
} else {
lib[browser_names[i]] = user_count[i];
}
}
This should give you the browser names and the cumulative user counts for each browser saved within object lib
Also, for the if conditional in the loop, you could also do:
for (var i=0; i < browser_names.length; i++) {
if (lib.hasOwnProperty(browser_names[i])) {
lib[browser_names[i]] += user_count[i];
} else {
lib[browser_names[i]] = user_count[i];
}
}
Also, I know your original question was an output to an array. You can easily loop through the keys of the object to get each of their respective browser names and user counts as well:
for (var k in lib) {
console.log(k); // Browser Names
console.log(lib[k]); // Their respective user counts
}
You could use a single loop and the help from an object as reference to the result arrays.
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"],
user_count = [3, 3, 3, 3, 7, 20, 94, 142],
result_browser_names = [],
result_user_count = [];
browser_names.forEach(function (b, i) {
if (!(b in this)) {
this[b] = result_browser_names.push(b) - 1;
result_user_count.push(0);
}
result_user_count[this[b]] += user_count[i];
}, Object.create(null));
console.log(result_browser_names);
console.log(result_user_count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Extracting multi-dimentsional arrays in Javascript/JQuery

I'm extracting some data from an SQL source, which I can get into a javascript script as a simple array (shown grouped by dates) which consists of week no, task number and hours spent:
mydata = [
// weekno, taskno, hours
["2014-14",160,37.5],
["2014-15",160,30],
["2014-15",243,7.5],
["2014-16",160,37.5],
["2014-17",0,7.5],
["2014-17",3,7.5],
["2014-17",321,22.5],
["2014-18",0,7.5],
["2014-18",321,30],
["2014-19",3,7.5],
["2014-19",295,30]
];
I'm going to be charting it using HighCharts, and I need to get it into two property arrays like this:
properties = {
categories: [ "2014-14","2014-15","2014-16","2014-17","2014-18","2014-19"],
series: [
// Task Week
// No 14 15 16 17 18 19
//
{ name: '0', data: [ 0, 0, 0, 7.5, 7.5, 0 ] },
{ name: '3', data: [ 0, 0, 0, 7.5, 0, 7.5 ] },
{ name: '160', data: [ 37.5, 30, 37.5, 0, 0, 0 ] },
{ name: '243', data: [ 0, 7.5, 0, 0, 0, 0 ] },
{ name: '295', data: [ 0, 0, 0, 0, 0, 30 ] },
{ name: '321', data: [ 0, 0, 0, 22.5, 30, 0 ] }
]
}
Aside from looping, am I missing some succinct, idiomatic method for doing this?
In case it's of use to anyone, here's a cobbled together solution:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
var categories = [];
var subcategories = [];
var temp = {};
for (var i = 0; i < myChartData.length; i++) {
key = myChartData[i][0];
taskno = myChartData[i][1];
hours = myChartData[i][2];
if (taskno in temp == false) temp[taskno] = {};
if (key in temp[taskno] == false) temp[taskno][key] = 0;
temp[taskno][key] += hours;
categories.push(myChartData[i][0]);
subcategories.push(myChartData[i][1])
}
var uniqueCategories = categories.filter(onlyUnique).sort();
var uniqueSubcategories = subcategories.filter(onlyUnique).sort(function(a, b) {
return a - b
});
var series = [];
for (var i = 0; i < uniqueSubcategories.length; i++) {
subcatKey = uniqueSubcategories[i];
series[i] = { name: 'Task ' + subcatKey, data: [] };
for (var j = 0; j < uniqueCategories.length; j++) {
catKey = uniqueCategories[j];
series[i]['data'].push(temp[subcatKey][catKey] ? temp[subcatKey][catKey] : 0);
}
}
where series and uniqueCategories are the required data.

Categories