How to rename field inside object - arrays

I found some solutions but not exactly what I wanted. I want to change the field name inside the object name where condition I will explain by the following example for if
array=[{
"mobile1": [{
"screensize": "6.5"
}]
},
{
"mobile2": [{
"screensize": "6.5"
},
{
"price": "2000"
}
]
}
]
I want to change mobile1 to newmobile final output will be
[{
"newmobile": [{
"screensize": "6.5"
}]
},
{
"mobile2": [{
"screensize": "6.5"
},
{
"price": "2000"
}
]
}
]

Try this:
let c = [{
"mobile1": [{
"screensize": "6.5"
}]
},
{
"mobile2": [{
"screensize": "6.5"
},
{
"price": "2000"
}
]
}
]
let final = c.map(i=>{
let x = Object.getOwnPropertyNames(i)
if(x=="mobile1"){
console.log(i.mobile1)
return {"newmobile":i.mobile1}
}
else {
return i
}
})
console.log("final output",final);

With input.map(i => { const {x, ...rest} = i; return x ? {...rest, a: x} : rest}) you should be able to change const input = [{x: 1, y: 2}, {x: 11, y: 22}, {z: 111, y: 222}] into [{y:2,a:1},{y:22,a:11},{z:111,y:222}].
Could this work for you?
UPDATE
My solution takes advantage of JavaScript's destructuring assignment with spread operatr. You can find below a running snippet:
const input = [{x: 1, y: 2}, {x: 11, y: 22}, {z: 111, y: 222}]
const output = input.map(i => { const {x, ...rest} = i; return x ? {...rest, a: x} : rest})
console.log(output)
So, in your case, you have
const input = [{
"mobile1": [{
"screensize": "6.5"
}]
},
{
"mobile2": [{
"screensize": "6.5"
},
{
"price": "2000"
}
]
}
]
const output = input.map(i => { const {mobile1, ...rest} = i; return mobile1 ? {...rest, newmobile: mobile1} : rest})
console.log(output)
and the produced output is the one you need.
I hope this can help you to solve your problem.

Related

How to add this GraphQL data to my pie chart in highcharts?

I would appreciate any help that I can get with this
I need to plot a pie chart with 4 standard pies: ABC, BCD, CDE and DEF
Each Pie has a data point coming in from my GraphiQL resolver which looks like this:
{
"data": {
"metrics": {
"A": 56147.85,
"B": 116480.51,
"C": 56147.85,
"D": 120329.45000000001,
}
}
}
This is my highchart code for piechart
function PieChart() {
const { loading, error, data } = useQuery(CONC, {
variables: {
Currency: 'USD',
Date: {
date: '2019-05-01',
date_range: ['2019-05-01', '2019-06-10'],
},
Options: {
a: {
prop: '44',
csprop: ['14', '14', '40', '60'],
},
d: {
prop: '104',
csprop: ['511', '289', '519', '62'],
},
},
C: 'G',
Incl: false,
DFilters: [
{
by: 'P',
values: [],
},
],
},
});
const Top = [];
const First = [];
const Second = [];
const Rest = [];
data &&
data.metrics.forEach((e) => {
Top.push(e['A']);
First.push(e['B']);
Second.push(e['C']);
Rest.push(e['D']);
});
return (
<HighchartWrapper
chartOptions={{
chart: {
type: 'pie',
height: 230,
// width: 565,
},
title: {
text: '',
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
},
accessibility: {
point: {
valueSuffix: '%',
},
},
exporting: {
enabled: false,
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
},
},
},
series: [
{
name: 'R',
data: [
{ name: 'ABC', y: Top},
{ name: 'BCD', y: First},
{ name: 'CDE', y: Second},
{ name: 'DEF', y: Rest},
],
},
],
}}
/>
);
}
export default memo(PieChart);
PROBLEM:
The GraphiQL query is generating results.
But I believe it's the way I am trying to push data that's giving me an empty pie chart
Thank you all in advance

Filter Array of Object from another Array of Object

Currently I'm filtering data based from questions that have checked property value equals to true..
const data = [
{Name: "foo", X1: "1", X2: "1", Other: "Test1"},
{Name: "bar", X1: "2",X2: "2",Other: "Test2"},
{Name: "test",X1: "2",X2: "3",Other: "Test3"}
];
const questions = [{rows: {text: "Text 1", checked: true,fields: "1",column: "X1"}
}, {rows: {text: "Text 2", checked: true,fields: "2",column: "X1"}
}, {rows: {text: "Text 3", checked: false,fields: "1",column: "X2"}
}, {rows: {text: "Text 4", checked: false,fields: "2",column: "X2"}
}, {rows: {text: "Text 5", checked: false,fields: "3",column: "X2"}
}];
console.log(questionArr);
// console.log(dataArr);
const res = data.filter(d => questions.find(f => d[f.rows.column] === f.rows.fields && f.rows.checked));
which works but does not work when filtering the actual data below. I think there's a slight difference between the question object and the actual question object below.. What should be my filter code when accessing these kind of structure ?
I think this is what you're looking for. I matched the data structure to the image in your question. Let me know if I missed something.
const data = [
{ Name: "foo", X1: "1", X2: "1", Other: "Test1" },
{ Name: "bar", X1: "2", X2: "2", Other: "Test2" },
{ Name: "test", X1: "2", X2: "3", Other: "Test3" }
];
const questions = [
{ rows: [{ text: "Text 1", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 2", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 3", checked: false, fields: "1", column: "X2" }] },
{ rows: [{ text: "Text 4", checked: false, fields: "2", column: "X2" }] },
{ rows: [{ text: "Text 5", checked: false, fields: "3", column: "X2" }] }
];
const result = data.filter(function(item){
return questions.some(function(question){
return question.rows.some(function(row){
return (row.checked && item[row.column] === row.fields);
});
});
});
console.log(result);
The compact version
const result = data.filter((item) => questions.some((question) => question.rows.some((row) => (row.checked && item[row.column] === row.fields))));
With perf in mind
const data = [
{ Name: "foo", X1: "1", X2: "1", Other: "Test1" },
{ Name: "bar", X1: "2", X2: "2", Other: "Test2" },
{ Name: "test", X1: "2", X2: "3", Other: "Test3" }
];
const questions = [
{ rows: [{ text: "Text 1", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 2", checked: true, fields: "2", column: "X1" }] },
{ rows: [{ text: "Text 3", checked: false, fields: "1", column: "X2" }] },
{ rows: [{ text: "Text 4", checked: false, fields: "2", column: "X2" }] },
{ rows: [{ text: "Text 5", checked: false, fields: "3", column: "X2" }] }
];
const result = {};
for(let a = 0, b = data.length; a < b; a++){
const item = data[a];
for(let c = 0, d = questions.length; c < d; c++){
const rows = questions[c].rows;
for(let e = 0, f = rows.length; e < f; e++){
const row = rows[e];
if(row.checked && item[row.column] === row.fields){
result[item.Name] = item;
break;
}
}
}
}
// this could be replaced with Object.values(result);
const matches = [];
for(let match in result){
matches.push(result[match]);
}
// not supported by IE yet
// Object.values(result);
console.log(matches);

Export Google Chart to Excel Sheet in Angular

Im using ng-google-chart to create charts from data I receive from a database. I store the data in a table. I need to export both the table and the chart.
I'm using the following technique to export tables (where "exportable" is the div the contains the table):
$scope.export = function ()
{
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Record.xls");
alert("export done");
};
I cannot find any way to add the chart to this file.
This is the code to generate a chart
var chart1 = {};
chart1.type = "ColumnChart";
chart1.cssStyle = "height:400px; width:500px;";
chart1.data = {
"cols": [
{ id: "gender", label: "Gender", type: "string" },
{ id: "number", label: "number", type: "number" }
], "rows": [
{
c: [
{ v: "male" },
{ v: $scope.male, f: $scope.male }
]
},
{
c: [
{ v: "female" },
{ v: $scope.female }
]
}
]
};
chart1.options = {
"title": "",
"isStacked": "true",
"fill": 20,
"displayExactValues": true,
"vAxis": {
"title": "Number", "gridlines": { "count": 6 }
},
"hAxis": {
"title": "gender"
}
};
chart1.formatters = {};
$scope.chart = chart1;
}
To getImageURI of the chart, wait for the ready event and call the function.
Then you can add the image somewhere on the page.
You can even hide the original chart if needed...
Following is an example of loading the image URI into another element.
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
google.visualization.events.addListener(chart, 'ready', function () {
document.getElementById("chart_image").insertAdjacentHTML('beforeEnd', '<img alt="Chart Image" src="' + chart.getImageURI() + '">');
});
chart.draw(view, options);
}
<script src="https://www.google.com/jsapi"></script>
<span>CHART</span>
<div id="chart_div"></div>
<br/>
<span>IMAGE</span>
<div id="chart_image"></div>

Currency format in google charts vs angular

I'm trying to add currency format in google charts and angularjs
Google charts display Money not Percentages
var formatter = new google.visualization.NumberFormat({
prefix: '$' }); formatter.format(data, 1);
var options = {
pieSliceText: 'value' };
how to add above code in the function below ?
$scope.jkchart = function(){
$scope.chartObject = {};
$scope.chartObject.data = {"cols": [
{id: "t", label: "Topping", type: "string"},
{id: "s", label: "Slices", type: "number"}
], "rows": [
{c: [
{v: "Mushrooms"},
{v: 3},
]},
{c: [
{v: "Olives"},
{v: 31}
]},
{c: [
{v: "Zucchini"},
{v: 5},
]}
]};
$scope.chartObject.type = "PieChart";
$scope.chartObject.options = {
'title': 'How Much Pizza I Ate Last Night'
};
};
You could specify format like this:
$scope.chartObject.formatters = {
number: [{
columnNum: 1,
prefix: '$'
}]
};
Working example
var app = angular.module('chartApp', ['googlechart']);
app.controller('MainCtrl', function ($scope) {
$scope.chartObject = {};
$scope.chartObject.data = {
"cols": [
{ id: "t", label: "Topping", type: "string" },
{ id: "s", label: "Slices", type: "number" }
], "rows": [
{
c: [
{ v: "Mushrooms" },
{ v: 3 },
]
},
{
c: [
{ v: "Olives" },
{ v: 31 }
]
},
{
c: [
{ v: "Zucchini" },
{ v: 5 },
]
}
]
};
$scope.chartObject.type = "PieChart";
$scope.chartObject.options = {
'title': 'How Much Pizza I Ate Last Night',
pieSliceText: 'value'
};
$scope.chartObject.formatters = {
number: [{
columnNum: 1,
prefix: '$'
}]
};
});
<script src="http://code.angularjs.org/1.2.10/angular.js"></script>
<script src="http://bouil.github.io/angular-google-chart/ng-google-chart.js"></script>
<body ng-app='chartApp' ng-controller="MainCtrl">
<div google-chart chart="chartObject" style="width: 900px; height: 500px;"></div>
</body>

EXTJS 5.1 VERY SIMPLE TreeStore from JSON

I have looked around but I still don't understand how to create treestore properly.
I have this very simple json that I get from a server:
{
"Results": [
{
"name": "John",
"age": 23,
"cars": [
{
"name": "Clio",
"brand": "Renault"
},
{
"name": "Class S",
"brand": "Mercedes"
}
]
},
{
"name": "Michel",
"age": 42,
"cars": [
{
"name": "Qashqai",
"brand": "Nissan"
}
]
}
]
}
I have my two models:
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: [ 'name', 'age']
});
Ext.define('Car', {
extend: 'Ext.data.Model',
fields: [ 'name', 'brand']
});
Now I know that I have to create a tree store, but in all example that I have seen, there is always a "children" property in the json, which I don't have.
How to create a tree store with the following json?
Thanks a lot in advance :) !!
You could always build the correct formatted object for the data like the following:
Ext.application({
name: 'Fiddle',
launch: function () {
var myTreeData = {
"Results": [{
"name": "John",
"age": 23,
"cars": [{
"name": "Clio",
"brand": "Renault"
}, {
"name": "Class S",
"brand": "Mercedes"
}]
}, {
"name": "Michel",
"age": 42,
"cars": [{
"name": "Qashqai",
"brand": "Nissan"
}]
}]
},
modifiedData = {
expanded: true,
children: []
};
myTreeData.Results.forEach(function (result) {
var newChildrenArray = [];
result.cars.forEach(function (car) {
var newChild = {
text: car.name,
leaf: true
};
newChildrenArray.push(newChild);
});
var person = {
text: result.name,
leaf: (newChildrenArray.length > 0 ? false : true),
children: newChildrenArray
};
modifiedData.children.push(person);
});
var store = Ext.create('Ext.data.TreeStore', {
root: modifiedData
});
Ext.create('Ext.tree.Panel', {
title: 'Simple Tree',
width: 200,
height: 150,
store: store,
rootVisible: false,
renderTo: Ext.getBody()
});
}
});
Demo here: https://fiddle.sencha.com/#fiddle/j05

Resources