Format json array to chart input - javascript

Hi i am getting json array as response of ajax request:
{"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05"
:0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}}
Now i want to prepare a chart by giving these values to chart input as below: ( i want output like this from above array )
data: [{
y: '2016-03-07',
a: 100
}, {
y: '2016-03-08',
a: 75
}, {
y: '2016-03-06',
a: 50
}, {
y: '2016-03-05',
a: 75
}, {
y: '2016-03-09',
a: 50
}, {
y: '2016-03-03',
a: 75
}, {
y: '2016-03-02',
a: 180
}
],
I have tried :
var chart_params = {};
for (var key in data_chart) {
let value = data_chart[key];
chart_params = '{ y:'+ key+ ', a: '+value+' }';
}
console.log(chart_params);
but it is not giving output as expected

Try this
data = {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05" :0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}}
var chart_params = [];
data_chart = data.chart;
for (var key in data_chart) {
var value = data_chart[key];
chart_params.push({ y: key, a:value});
}
console.log(chart_params);
jsfiddle: https://jsfiddle.net/hb8qd1p8/1/

#madalin's answer is the correct fix for your issue, though another option to accomplish what you want is to use map:-
var data = {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05":0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}};
var array = Object.keys(data.chart).map(function (key) {
return { y: key, a: data.chart[key] };
});
document.write(JSON.stringify(array, null, 4));

Related

FInd duplicates withtin array based on certain keys using lodash?

I have an array like this
let data = [{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3}]
Now I want to get only those items whose x,y,z values are the same.so expected output should be
{x:1,y:2,z:3}
Because {x:1,y:2,z:3} has duplicate values but rest of them not so I don't want to get rest of them because they do not have any duplicates. Please tell me how can I achieve this?
For lodash 4.17.15,
You can first use _.uniqWith and _.isEqual to find the unique values.
_.uniqWith(data, _.isEqual); // [{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3}]
Then use _.difference to remove the unique values from the array, leaving just the duplicates
_.difference(data, _.uniqWith(data, _.isEqual)); // [{x:1,y:2,z:3}]
let data = [{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3},{x:11,y:2,z:3}]
function filterDuplicates(data) {
let dic = {};
data.forEach(obj => {
let strObj = JSON.stringify(obj, Object.keys(obj).sort());
if(strObj in dic) {
++dic[strObj];
return;
}
dic[strObj] = 0;
})
return Object.entries(dic).filter(([key, value]) => value > 0).map(([el]) => JSON.parse(el));
}
console.log(filterDuplicates(data));
Build an object to track the duplicates and use Object.values and filter
let data = [
{ x: 1, y: 2, z: 3 },
{ x: 1, y: 2, z: 3 },
{ x: 1, y: 2, z: 4 },
{ x: 11, y: 2, z: 3 },
];
const all = {};
data.forEach(({ x, y, z }) => {
const key = `x${x}y${y}z${z}`;
all[key] = key in all ? { x, y, z } : null;
});
const res = Object.values(all).filter(Boolean);
console.log(res);

Javascript Map function does not preserve the original object

I have a scenario wherein i have
var data = [
{
"x": 1,
"y": 0.27,
"classifier": 1
},
{
"x": 2,
"y": 0.88,
"classifier": 1
}
]
I want another object data2 with y=1-y, which i obtain with:
var data2 = data.map(function(el) {el.y = 1-el.y; return el});
data2[0]
Object {x: 1, y: 0.73, classifier: 1}
data2[1]
Object {x: 2, y: 0.12, classifier: 1}
which is the correct form that i want the data in. However the issue is i want to preserve the original data as well. Right now even data has mutated data.
data[0]
Object {x: 1, y: 0.73, classifier: 1}
data[1]
Object {x: 2, y: 0.12, classifier: 1}
Is map the right function to use here? Am i using it correctly?
While creating a new array, you let its values point to the original objects, which you mutate by assigning to their object properties.
Instead you could also create (shallow) copies of the objects with Object.assign:
var data2 = data.map(function(el) {
return Object.assign({}, el, { y: 1-el.y });
});
Or with arrow function:
var data2 = data.map( el => Object.assign({}, el, { y: 1-el.y }) );
var data = [
{
"x": 1,
"y": 0.27,
"classifier": 1
},
{
"x": 2,
"y": 0.88,
"classifier": 1
}
]
var data2 = data.map( el => Object.assign({}, el, { y: 1-el.y }) );
console.log (data);
You're modifying the original element object, which isn't a full deep copy of the original data.
Create a copy of el in the function and then calculate the new .y. For example:
var data2 = data.map(function(el) {
return {
x : el.x,
y : 1-el.y,
classifier : el.classifier
};
});

iterate the json array and push each value to the list in angular js

I am very new to angular JS.My question is, I have a json array that I am getting as ajax response from php page. I am iterating that json array and I want to push each value in the list like
angular.forEach($scope.companies.area, function(value, key) {
$scope.comp = [
{ 'name': value1 },
{ 'name': value2 },
{ 'name': value3 }
//...
]
});
How can I make this list?
My Json data is
{"1":"Audugodi","2":"Airforce Station Yelahanka","3":"Agaram","4":"Anadanagar","5":"Arabic College","6"
:"Banasawadi","7":"Banashankari","8":"Banashankari II Stage","9":"Banashankari III Stage","10":"Bangalore
city","11":"Bangalore GPO","12":"Bannerghatta","13":"Bannerghatta Road","14":"Basavanagudi","15":"Basaveswaranagar"
}
It can be easier using a simple Array.prototype.map:
$scope.comp = $scope.companies.area.map(function(value) {
return { name: value };
});
As your data is actually in an object format, will have to change a bit to use it with .map (the original JSON data is at the bottom for reference):
helloApp.controller("CompanyCtrl", function ($scope, $http) {
$http.post('class_locaality.php?flag=1').success(function (data) {
$scope.companies = data; // the original data - we need data.area
$scope.comp = Object.keys(data.area).map(function (key) { // turn the object into a array of keys that we can iterate
return {
name : data.area[key] // get the value from the original data.area using the key
};
});
}).error(function (data) { // log error }); });
{
"1" : "Audugodi",
"2" : "Airforce Station Yelahanka",
"3" : "Agaram",
"4" : "Anadanagar",
"5" : "Arabic College",
"6" : "Banasawadi",
"7" : "Banashankari",
"8" : "Banashankari II Stage",
"9" : "Banashankari III Stage",
"10" : "Bangalore city",
"80" : "St.Thomas Town",
"81" : "Subramanyanagar",
"95" : "Yelahanka",
"96" : "Yeshwanthpur"
}
This isn't very specific to Angular. You can do exactly as you say: push the values into the array:
$scope.comp = [];
$scope.companies.area.forEach(function(value) {
$scope.comp.push({ name: value });
});
An example copied from here without using .Map
var colors = [
{r: 255, g: 255, b: 255 }, // White
{r: 128, g: 128, b: 128 }, // Gray
{r: 0, g: 0, b: 0 } // Black
];
var newColors = [];
for (var i = 0; i < colors.length; i++) {
transformed = {
r: Math.round( colors[i].r / 2 ),
g: Math.round( colors[i].g / 2 ),
b: Math.round( colors[i].b / 2 )
};
newColors.push(transformed);
}
// Outputs:
// [
// {r: 128, g: 128, b: 128 },
// {r: 64, g: 64, b: 64 },
// {r: 0, g: 0, b: 0 }
// ];
console.log(newColors);
Using .map
var newColors = colors.map(function(val) {
return {
r: Math.round( val.r / 2 ),
g: Math.round( val.g / 2 ),
b: Math.round( val.b / 2 )
};
});
For explanation read this excellent article

Javascript JSON not working after parsing

I need to get graph generated from Mysql database with help of PHP. I got nice application from (http://canvasjs.com). So, I created my own JSON format in variable element from PHP SESSION. It gies me no error when debugged, but no result.
Line number 34 - 37 gives me graph if I don't comment them. When comment them and replace with my own JSON which is variable element and does not give me graph. Gives me blank page.
I am new to JSON. Help me out with this.
Following are my codes.
var array = <?php echo json_encode($_SESSION["r_array"]); ?>;
var count = 0;
var element = '';
var title = 'Malware lab, TCRC, CTA';
for( var i in array) {
if ( count == 0 ) {
element += ‘{y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
} else {
element += ‘, {y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
}
count++;
}
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: [
/*
34 {y: 2, indexLabel: “Kaka'”},
35 {y: 3, indexLabel: “Blackberry”},
36 {y: 1, indexLabel: “Windows Phone”},
37 {y: 5, indexLabel: “Others”},*/
element,
]
}
]
});
chart.render();
Dumped array of $_SESSION["r_array"] as following
Array (
[Trojan] => 1
[Malware] => 3
[Backdoor] => 6
[Virus] => 2
[Bot] => 5
[Rootkit] => 7
[Worm] => 5
)
element must be an array, you are trying to create it as a string(with syntax errors)
var array = <? php echo json_encode($_SESSION["r_array"]); ?> ;
var count = 0;
var element = [];
var title = 'Malware lab, TCRC, CTA';
for (var i in array) {
element.push({
y: array[i],
indexLabel: i
})
count++;
}
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: title
},
data: [{
type: type,
dataPoints: element
}]
});
chart.render();
Demo: Fiddle
Yo need to pass array in correct Way
Use another variable datapoints = [];
and the push object into that array
var datapoints = [];
for( var i in array) {
datapoints.push({ y : array[i] , indexLabel : i});
}
and then use it as below
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: datapoints
}
]
});
chart.render();

How to convert an object into nested object

How can I transform the following:
{
Eldoret: "900",
Nairobi: "1900"
}
into:
[
{
y:"Eldoret",
a: 900
},
{
y:"Nairobi",
a:1900
}
]
using JavaScript. I've tried using the following snippet but it just picks on the last property
for(var key in data3){
if(data3.hasOwnProperty(key)){
data_obj.y = key;
data_obj.a = data3[key];
}
Output:
{
y: "Nairobi",
a: "1900"
}
You iterate over your keys:
var myobj = { .... };
var objKeys = Object.keys(myobj);
var reformatted = objKeys.map(function(key) {
return {
x: key,
y: myobj[key]
};
});
You can build up the result step-by-step by appending items to a new array in your loop:
data3 = {
Eldoret: "900",
Nairobi: "1900"
}
res = []
for (var key in data3) {
res.push({
y: key,
a: data3[key],
})
}
console.log(res)

Categories

Resources