how to bind the unique value for Domicile Name from json into the Dropdown in angularjs - angularjs-directive

Array is this:
$scope.domicile = {};
$scope.domicile.users = [
{ DomicileName: 'European', PortFolioName: 'nternational Select x EM ADR', Alias: 'ADR x EM', Percentage: 1.0, Ticker: 'ADR', Category: 'ADRxEM', SortOrder: 1 },
{ DomicileName: 'European', PortFolioName: 'International Select x EM ORD', Alias: 'Ord x EM', Percentage: 4, Ticker: 'ORD', Category: 'ADRxEM', SortOrder: 1 },
{ DomicileName: 'European', PortFolioName: 'International Select with EM ADR', Alias: 'ADR w EM', Percentage: 4, Ticker: 'ADR', Category: 'ADRwEM', SortOrder: '' },
{ DomicileName: 'Developed Market Non-European', PortFolioName: 'International Select x EM ADR', Alias: 'ADR x EM', Percentage: 4, Ticker: 'ADR', Category: 'ADRxEM', SortOrder: 1 }
];
enter code here

$scope.fetched = [];
angular.forEach($scope.domicile.users, function(value, key) {
if (value["DomicileName"] === "European") {
$scope.fetched.push($scope.domicile.users[key]); // add to array
}
})

Filter data of $scope.domicile.users like this
$scope.domicile = $scope.domicile.users.filter(function(val) {
return val['DomicileName'] == 'European'
});
console.log($scope.domicile);

Assuming that you want to push the data into $scope.fetched = [] array, just write this in your code:
$scope.fetched = $scope.domicile.users.filter(function(user) {
return user.DomicileName === 'European';
});

Related

JSON data calculation and re-formate using Angular

I have a JSON file and I am trying to calculate the JSON file key based on the value and reformating it. My JSON file looks like below:
data=[
{
pet:'Cat',
fruit:'Apple',
fish:'Hilsha'
},
{
pet:'Dog',
fish:'Carp'
},
{
pet:'Cat',
fruit:'Orange',
fish:'Lobster'
}
];
I do like to calculate and formate it like below:
data=[
{
label:'Pet',
total:3,
list:[
{
name:'Cat',
value: 2,
},
{
name:'Dog',
value: 1,
}
]
},
{
label:'Fruit',
total:2,
list:[
{
name:'Apple',
value: 1,
},
{
name:'Orange',
value: 1,
}
]
},
{
label:'Fish',
total:3,
list:[
{
name:'Hilsha',
value: 1,
},
{
name:'Carp',
value: 1,
},
{
name:'Lobster',
value: 1,
}
]
},
];
If anybody can help me, it will be very help for me and will save a day.
I have fixed this task myself. If I have any wrong, you can put your comment fill-free :)
``
ngOnInit(): void {
this.dataService.$data.subscribe(data => {
// Create new object and calculation according to category
let petObj: any = {}
let fruitObj: any = {}
let fishObj: any = {}
data.forEach((el: any) => {
if (el.pet != undefined) {
petObj[el.pet] = (petObj[el.pet] || 0) + 1;
}
if (el.fruit != undefined) {
fruitObj[el.fruit] = (fruitObj[el.fruit] || 0) + 1;
}
if (el.fish != undefined) {
fishObj[el.fish] = (fishObj[el.fish] || 0) + 1;
}
});
// Create list according to category
let pet_list: any = [];
let fruit_list: any = [];
let fish_list: any = [];
for (var key in petObj) {
let pet = {
label: key,
value: petObj[key]
}
pet_list.push(pet)
}
for (var key in fruitObj) {
let fruit = {
label: key,
value: fruitObj[key]
}
fruit_list.push(fruit)
}
for (var key in fishObj) {
let fish = {
label: key,
value: fishObj[key]
}
fish_list.push(fish)
}
// Calculate total sum according to category
var totalPet = pet_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
var totalFruit = fruit_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
var totalFish = fish_list.map((res: any) => res.value).reduce((a: any, b: any) => a + b);
// Rearrange the JSON
this.rearrangeData = [
{
label: 'Pet',
total: totalPet,
list: pet_list
},
{
label: 'Fruit',
total: totalFruit,
list: fruit_list
},
{
label: 'Fish',
total: totalFish,
list: fish_list
}
]
console.log(this.rearrangeData)
// End rearrange the JSON
});
}
``
You can simplify your function. Take a look this one
group(oldData) {
const data = []; //declare an empty array
oldData.forEach((x) => {
//x will be {pet: 'Cat',fruit: 'Apple',fish: 'Hilsha'},
// {pet: 'Dog',fish: 'Carp'}
// ...
Object.keys(x).forEach((key) => {
//key will be 'pet','fruit',...
const item = data.find((d) => d.label == key); //search in the "data array"
if (item) { //if find it
item.total++; //add 1 to the property total of the element find it
// and search in the item.list the 'Cat'
const list = item.list.find((l) => l.name == x[key]);
//if find it add 1 to the property value of the list
if (list)
list.value++;
else
//if not, add to the list
//an object with property "name" and "value" equal 1
item.list.push({ name: x[key], value: 1 });
} else
//if the element is not in the "array data"
//add an object with properties label, total and list
//see that list is an array with an unique element
data.push({
label: key,
total: 1,
list: [{ name: x[key], value: 1 }],
});
});
});
return data;
}
You can use like
this.dataService.$data.subscribe(data => {
this.rearrangeData=this.group(data)
}
NOTE: this function the labels are 'pet','fruit' and 'fish' not 'Pet', 'Fruit' and 'Fish'
Did you try reading the text leading up to this exercise? That'd be my first approach. After that, I'd use reduce. You can do pretty much anything with reduce.

How to import and use a custom Chart.js plugin in Nuxt? (Chartjs-vuejs v2.9.4)

I am trying to import a custom plugin into my chart.
Got this plugin from my previous question: Question
Its a plugin so that I can use Grace in my version of Chart.js.
The version of Chart.js I am using is V2.9.4.
I am using vue-chartjs in Nuxt!.
Couldn't really find an answer anywhere else.
This is how it looks now
This is how I want it to look
Thanks in advance. :)
I made a Component called 'BarChart' in my Components folder.
I made a normal .vue file in my pages directory. In the <template> tag I added my <Barchart/> component.
In that same .vue file I added a script in the <script> tag.
The plugin code is included in the codes below, I didn't include it anywhere yet.
Barchart.vue (Component)
<script>
import {Bar} from "vue-chartjs";
export default {
extends: Bar,
props: {
data: {
type: String,
default: () => {},
},
options: {
type: Object,
default: () => {},
},
},
computed: {
Chart() {
return['data', 'options'];
},
},
mounted() {
this.renderChart(this.data, this.options);
},
};
</script>
.vue file (Include component)
<div class="chart">
<BarChart :data="barChartData" :options="barChartOptions" :height="200"/>
</div>
.vue file (script tags)
<script>
import BarChart from "~/components/plugins/BarChart";
export default {
components: {
BarChart,
},
data() {
return {
barChartData: {
labels: ["Verzonden", "Ontvangen", "Geopend", "Kliks"],
datasets: [
{
data: [25, 20, 20, 18],
backgroundColor: [
'#7782FF',
'#403DD3',
'#FFB930',
'#00E437',
],
barThickness : 50,
},
],
},
barChartOptions: {
responsive: true,
legend: {
display: false,
},
scales: {
xAxes: [
{
gridLines: {
display: false,
},
ticks: {
fontColor: "black",
fontSize: 14,
},
},
],
yAxes: [
{
ticks: {
beginAtZero: true,
min: 0,
stepSize: 5,
fontColor: '#ABACB3',
},
gridLines: {
display: true,
borderDash: [4, 4],
color: '#EEEDFB',
drawBorder: false,
},
},
],
},
},
};
},
};
</script>
Plugin code (where do I put this and how do I make it work?)
const plugin = {
id: "customScale",
beforeLayout: (chart, options, c) => {
let max = Number.MIN_VALUE;
let min = Number.MAX_VALUE
let grace = options.grace || 0
chart.data.datasets.forEach((dataset) => {
max = Math.max(max, Math.max(...dataset.data));
min = Math.min(min, Math.min(...dataset.data))
})
if (typeof grace === 'string' && grace.includes('%')) {
grace = Number(grace.replace('%', '')) / 100
chart.options.scales.yAxes[0].ticks.suggestedMax = max + (max * grace)
chart.options.scales.yAxes[0].ticks.suggestedMin = min - (min * grace)
} else if (typeof grace === 'number') {
chart.options.scales.yAxes[0].ticks.suggestedMax = max + grace
chart.options.scales.yAxes[0].ticks.suggestedMin = min - grace
}
}
}
According to the vue-chartjs documentation you can do this in 2 ways.
If you want the plugin to be available for all your charts you can use the global registration like so:
import Chart from 'chart.js'
Chart.pluginService.register({
id: "customScale",
beforeLayout: (chart, options, c) => {
let max = Number.MIN_VALUE;
let min = Number.MAX_VALUE
let grace = options.grace || 0
chart.data.datasets.forEach((dataset) => {
max = Math.max(max, Math.max(...dataset.data));
min = Math.min(min, Math.min(...dataset.data))
})
if (typeof grace === 'string' && grace.includes('%')) {
grace = Number(grace.replace('%', '')) / 100
chart.options.scales.yAxes[0].ticks.suggestedMax = max + (max * grace)
chart.options.scales.yAxes[0].ticks.suggestedMin = min - (min * grace)
} else if (typeof grace === 'number') {
chart.options.scales.yAxes[0].ticks.suggestedMax = max + grace
chart.options.scales.yAxes[0].ticks.suggestedMin = min - grace
}
}
});
This way of importing and registering should work from anywhere in your app.
The second way is an inline plugin. This needs to be done in your BarChart.vue and goes like this:
mounted() {
this.addPlugin(
Chart.pluginService.register({
id: "customScale",
beforeLayout: (chart, options, c) => {
let max = Number.MIN_VALUE;
let min = Number.MAX_VALUE
let grace = options.grace || 0
chart.data.datasets.forEach((dataset) => {
max = Math.max(max, Math.max(...dataset.data));
min = Math.min(min, Math.min(...dataset.data))
})
if (typeof grace === 'string' && grace.includes('%')) {
grace = Number(grace.replace('%', '')) / 100
chart.options.scales.yAxes[0].ticks.suggestedMax = max + (max * grace)
chart.options.scales.yAxes[0].ticks.suggestedMin = min - (min * grace)
} else if (typeof grace === 'number') {
chart.options.scales.yAxes[0].ticks.suggestedMax = max + grace
chart.options.scales.yAxes[0].ticks.suggestedMin = min - grace
}
}
});
)
}

Getting usable numbers from Nested Array Json

My data that I'm given is formulated like the following. I'm struggling to get any usable data out of it using reduce or map
const data = [
{
id: 25,
status: 1,
description: "No Description",
length: 4,
data: [
{
id: 43,
comment: "Comment1",
eventTimestamp: 1541027189000,
intensity: 29
},
{
comment: "Comment2",
eventTimestamp: 1541027191000,
intensity: 33
},
{
id: 45,
comment: "Comment3",
eventTimestamp: 1541027193000,
intensity: 30
}
],
tTypes: [
{
id: 3,
label: "Johnny",
certainty: "TEST",
comment: "Test Purposes Only",
icon: "bottle",
number: 0
}
]
}
];
I've tried flatting, I've tried iterating the JSON twice and I just seem to end up with either "NaN" or Undefined. I'd like to be able to order them in time order (using time stamp), get the mix/max/ave from the intensity values and more. I have that figured out for the length which is a level higher, but just can't seem to figure out the rest. Can someone point me in the right direction?
export default function App() {
let tTypesArray = data.map((a) => a.tTypes);
let Walker = tTypesArray.reduce((a, tTypes) => tTypes.label === "Johnny" ? ++a : a, 0);
console.log(Walker);
console.log(tTypesArray[0].label);
console.log([].concat(...data)
.map(data => data.tTypes.number)
.reduce((a, b) => a + b))
console.log([].concat(...data).reduce((a, { tTypes: { id }}) => id, 0))
return <div className="App">ARG!</div>;
}
Are some of the examples I've tried.
https://codesandbox.io/s/purple-cache-ivz1y?file=/src/App.js
Is the link to the sandbox.
What I understood from you question is that you need to loop data and for each element in data you want to extract values and do some calculations.
First you need to loop your data input. I will use Array.forEach:
data.forEach(element => { ... })
Now that we have a loop we can access each element property and extract the information we want. For instance lets say you want to sort the comments by timestamp in ascending order:
const sortedComments = element.data.sort((a, b) => a.eventTimestamp - b.eventTimestamp);
console.log(sortedComments)
Now let's say you want the min, max, and average intensity from the comments. There are several ways to get it. Here is an algorithm for that:
let min = Infinity;
let max = -Infinity;
let sum = 0;
for(comment of sortedComments) {
if(comment.intensity < min) {
min = comment.intensity;
}
if(comment.intensity > max) {
max = comment.intensity;
}
sum += comment.intensity;
}
const avg = sum / sortedComments.length;
console.log({min, max, avg})
Putting it all together:
const data = [
{
id: 25,
confirmationStatus: 1,
description: "No Description",
length: 4,
data: [
{
id: 43,
comment: "Comment1",
eventTimestamp: 1541027189000,
intensity: 29
},
{
comment: "Comment2",
eventTimestamp: 1541027191000,
intensity: 33
},
{
id: 45,
comment: "Comment3",
eventTimestamp: 1541027193000,
intensity: 30
}
],
tTypes: [
{
id: 3,
label: "Johnny",
certainty: "TEST",
comment: "Test Purposes Only",
icon: "bottle",
number: 0
}
]
}
];
data.forEach(element => {
const sortedComments = element.data.sort((a, b) => a.eventTimestamp - b.eventTimestamp);
console.log(sortedComments);
let min = Infinity;
let max = -Infinity;
let sum = 0;
for(comment of sortedComments) {
if(comment.intensity < min) {
min = comment.intensity;
}
if(comment.intensity > max) {
max = comment.intensity;
}
sum += comment.intensity;
}
const avg = sum / sortedComments.length;
console.log({min, max, avg});
let walker = element.tTypes.reduce(
(a, tType) => (tType.label === "Johnny" ? ++a : a), 0
);
console.log(walker)
});
I hope it puts you in the right direction.

Ajax Response Capitalizations Rules

A was using DataTables plugin, and when displaying my columns I needed to put the first letter to LowerCase for it to recognize the property/object, e.g:
// Object name is actually: EngineeringChange.Responsible
{
title: "Responsible",
data: "engineeringChange.responsible",
className: "columnName columnHeader",
},
I just assumed the first letter would always be capitalized to LowerCase. I tried creating a new property inside EngineeringChange named ECRNumber, so I tried:
{
title: "ECR Number",
data: "engineeringChange.eCRNumber",
className: "columnName columnHeader",
},
Isn't recognized as a parameter... After a bit of searching I find out the Json response I get on AJAX it's called ecrNumber. So now I'm actually lost on which are the rules that are automatically applied to the Json Response. How does it turn ecr to LowerCase and Number to UpperCase (the N)??
Edit
Sry, can´t think of any easy way to exactly reproduce my problem on a demo
TableDesign/Creation
table = $('#tblEntries2').DataTable({
order: [[0, 'desc']],
deferRender: true,
ajax: {
url: '#Url.Action("GetEntries", "AlteracaoEngenharia")',
method: 'GET',
dataSrc: '',
beforeSend: function () {
onBegin();
$content.hide();
$loader.show();
},
complete: function (jsonResponse) {
console.log(jsonResponse);
onComplete();
$loader.hide();
$content.fadeIn();
$('#ExcelExport').show();
table.column(5).visible(false);
table.column(6).visible(false);
table.column(7).visible(false);
table.column(9).visible(false);
table.column(10).visible(false);
table.column(11).visible(false);
}
},
dom: "<'row'<'col-2'l><'col-7 text-center'B><'col-3'f>>" +
"<'row'<'col-12'tr>>" +
"<'row'<'col-5'i><'col-7'p>>",
lengthMenu: [
[10, 25, 50, 100, -1],
['10', '25', '50', '100', 'Todos'],
],
columns: [
{
title: "Id (yr-id)",
data: "creationYear",
className: "columnNumber columnHeader",
},
{
title: "ECR Number",
data: "engineeringChange.ecrNumber",
className: "columnNumber columnHeader",
},
{
title: "Criador Alteração de Engenharia",
data: "engineeringChange.responsible",
className: "columnName columnHeader",
},
...
Handler
public IActionResult GetEntries()
{
GetDataEntries();
int count = 0;
int currentYear = 0;
foreach (var entry in EntriesList)
{
EngineeringChangesListViewModel h = new EngineeringChangesListViewModel
{
EngineeringChange = entry
};
if (currentYear != entry.DataCriacao.Year)
{
count = 1;
currentYear = entry.DataCriacao.Year;
}
else
{
count++;
}
h.DeadLine = entry.FinishedGood.Week + " - " + entry.DataCriacao.Year.ToString();
if (entry.OldPart == null)
{
h.EngineeringChange.OldPart = new Part();
}
if (entry.NewPart == null)
{
h.EngineeringChange.NewPart = new Part();
}
if (entry.FinishedGood == null)
{
h.EngineeringChange.FinishedGood = new FinishedGood();
}
if (entry.OldPart != null && entry.OldPart.CDP.HasValue)
h.OldPartValue = entry.OldPart.CDP * entry.OldPart.Stock;
if (entry.NewPart != null && entry.NewPart.CDP.HasValue)
h.NewPartValue = entry.NewPart.CDP * entry.NewPart.Stock;
h.EngineeringChange.ECRNumber = entry.ECRNumber;
//toString("D4") padds the number to always be 4 digits
h.CreationYear = entry.DataCriacao.Year.ToString() + "_" + count.ToString("D4");
h.IdYear = count;
EntriesListaViewModel.Add(h);
}
var errorsJson = JsonConvert.SerializeObject(EntriesListaViewModel);
Console.WriteLine(errorsJson);
return new JsonResult(EntriesListaViewModel);
}
HANDLER OUTPUT
[{"CreationYear":"2021_0001","IdYear":1,"OldPartValue":null,"NewPartValue":2061.09155,"DeadLine":"15 - 2021","EngineeringChange":{"Id":8,"DataCriacao":"2021-03-11T16:15:24.6630956","Responsible":"José António","ECRNumber":"X1232","State":"Aberto","Comment":"Teste","UserId":1,"User":null,"Component":null,"FinishedGood":{"Id":31,"Week":15,"EngineeringChangeId":8},"OldPart":{"Id":5,"Reference":"FS12848AC","Stock":null,"CDP":1.43584776,"LastExpired":null},"NewPart":{"Id":6,"Reference":"FS12848AD","Stock":1650,"CDP":1.24914646,"LastExpired":"2021-03-11T00:00:00"},"Transformation":{"Id":188,"Possible":true,"Cost":1090.0,"WillBeTransformed":true,"TransformationDate":"2021-03-13T08:48:00","Responsible":"Miguel","EngineeringChangeId":8}}},]
PAGE/AJAX OUTPUT outputs are created by console.log() and Console.WriteLine() displayed above.
ECRNumber gets named to ecrNumber...

How to get values from json object array and add to another array in angular

I have Following json object :
var arr =[{
0:M: "LED"
id: 1
mtype: "KIOSK PACKAGE"
part_fees: 200
tb_bid_upins: 1
tech_bid_flag: 0
tot_media: 0
type: "Road Stretch"
upin: "AMCADVT1415C0123"
upin_id: "2"
}, {
1:M: "LED"
id: 1
mtype: "KIOSK PACKAGE"
part_fees: 200
tb_bid_upins: 1
tech_bid_flag: 0
tot_media: 0
type: "Road Stretch"
upin: "AMCADVT1415C0123"
upin_id: "2"
}]
Now it has two values,but it can have multiple value because it is fetch from database.
From this json i wnat to pick values with key upin,mtype,land and add to another array.
I have tried following
for(let item of data){
// this.console.log(item)
this.upins = item.upin;
this.console.log(this.upins);
}
this.console.log(this.upins);```
It shows last index value
I want result as follows
var arr = [{
upins: abc,
mtyp:xyz,
land:123
},{
upins:123,
mtype:pqr,
land:555
}]
Assuming data as array you should insert data in a new empty array.
const arr = [];
// extract upin, mtype, land from the original array
for (let item of data) {
arr.push({
upin: item.upin,
mtype: item.mtype,
land: item.land
});
}
// OR
const arr = data.map((item) => {
return {
upin: item.upin,
mtype: item.mtype,
land: item.land
};
});
You can use map and destructing method for your requirement, you can include what properties you need. I did not see land property in your data.
const result = arr.map(({ upin, mtype }) => ({
upin, mtype
}));
var arr =[{ id: 1,
mtype: "KIOSK PACKAGE",
part_fees: 200,
tb_bid_upins: 1,
tech_bid_flag: 0,
tot_media: 0,
type: "Road Stretch",
upin: "AMCADVT1415C0123",
upin_id: "2"
}, {
id: 1,
mtype: "KIOSK PACKAGE",
part_fees: 200,
tb_bid_upins: 1,
tech_bid_flag: 0,
tot_media: 0,
type: "Road Stretch",
upin: "AMCADVT1415C0123",
upin_id: "2" }]
const result = arr.map(({ upin, mtype }) => ({
upin, mtype
}));
console.log(result);
this is pure javascript and it has nothing to do with angular. you can use map function to transform arrays.
const arr2 = this.arr.map(el => ({upins: el.upins, mtyp: el.mtyp, land: el.land}));
The first answer is right. I only want to add that you can use map method for same goal. It's more comfortable for me:
const newData = data.map(x => {
return {
upin: x.upin,
mtype: x.mtype,
land: x.land
};
});
Map will check each element in the array and return new object based on element properties.