i have json array get from http web api, i want to filter this array:
[
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}]
i need to filter or select for get all where id_segmen=1.
this is my expectation :
[
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
}]
my current http.get is as below:
this.http.get<JuResponse>(environment.url + '/cps/' + year + '/' + month + '/' + kanwil + '/' + cabang).
subscribe(data => {
let filteredValues = data.filter((data) => value.id_segmen == 1);
console.log(filteredValues);
});
Check the below code, items is your JSON from WebAPI and fiteredItem is an array of objects which has id_segmen=1
this.filteredItem= this.items.filter((item) => {
return (item.id_segmen ===1);
})
You can use
for (var i = 0; i < arrayData.length; i++) {
if (arrayData[i].id_segmen == 1) {
result.push(arrayData[i]);
}
}
Try this
var arrayData= [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}]
var result = [];
for (var i = 0; i < arrayData.length; i++) {
if (arrayData[i].id_segmen == 1) {
result.push(arrayData[i]);
}
}
console.log(result)
You can use Array.filter
let filteredArray = this.myArray.filter(item => item.id_segment===1)
Simply use the native javascript filter() method, like this way:
let filteredValues = result.filter((value) => value.id_segmen == 1);
this way,
filteredValues will contain only your values with id_segmen == 1.
You can use Javascript Filters for this purpose
var a = [
{
"bulan": "4",
"tahun": "2017",
"id_program": 4,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 3953,
"target": 900000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 2,
"segmen": "bpu",
"jumlah": 45,
"target": 500000
},
{
"bulan": "4",
"tahun": "2017",
"id_program": 3,
"id_segmen": 1,
"segmen": "ppu",
"jumlah": 8752,
"target": 900000
}];
var c = a.filter(function(val){
return val.id_segmen == 1 ;
});
alert(JSON.stringify(c))
Related
I need to convert a data like this:
{peopleList: [{id:1, name: 'joe'}, {id: 2, name: 'john'}], page: 1, rowPerPage: 8}
to this model:
{entities: {'0': {id: 0, name: 'joe'}, '1': {id: 1, name: 'john'}, page: 1, rowPerPage: 8}, result: [0, 1]}
but when I add this schema:
const people = new schema.Entity('peopleList');
const normalizedData = normalize(_data, { peopleList: [people] });
I get this output:
{
"entities": {
"peopleList": {
"1": {
"id": 1,
"name": "joe"
},
"2": {
"id": 2,
"name": "john"
}
}
},
"result": {
"peopleList": [
1,
2
],
"page": 1,
"rowPerPage": 8
}
}
I don't know exactly how to make a proper schema that create result filed as my desire. maybe the correct way is to have it in result and this output is correct. any idea?
i want to grouping data JSON (One JSON) base on region. and the json after grouping like in (Two JSON). and i use the two JSON for show data (Result JSON). so, how to add loop base on region after grouping, because actually i want to show data in front end like (Result JSON):
==>One JSON
data:[
{id:1,
status: "active",
dataDetail: {
id: 5,
name: tes 1,
region: aaa,
}
},
{id:2,
status: "active",
dataDetail: {
id: 8,
name: tes 2,
region: bbb,
}
},
{id:3,
status: "active",
dataDetail: {
id: 8,
name: tes 3,
region: aaa,
}
}
]
==> Two JSON
aaa: [
{id:1,
status: "active",
dataDetail: {
id: 5,
name: tes 1,
region: aaa,
}
},
{id:3,
status: "active",
dataDetail: {
id: 8,
name: tes 3,
region: aaa,
}
}
],
bbb: [
{id:2,
status: "active",
dataDetail: {
id: 8,
name: tes 2,
region: bbb,
}
},
]
==> Result JSON
aaa:
1
3
bbb:
2
thanks
Using Lodash:
const jsonTwo = _.groupBy(data, instance => instance.dataDetail.region);
const resultJson = _.mapValues(jsonTwo, regionInstances => regionInstances.map(instance => instance.id));
Using plain javascript reduce functions:
const jsonTwo = data.reduce((accumulator, instance) => {
if(!accumulator[instance.dataDetail.region]) {
accumulator[instance.dataDetail.region] = [];
}
accumulator[instance.dataDetail.region].push(instance)
return accumulator;
},{});
const resultJson = data.reduce((accumulator, instance) => {
if(!accumulator[instance.dataDetail.region]) {
accumulator[instance.dataDetail.region] = [];
}
accumulator[instance.dataDetail.region].push(instance.id)
return accumulator;
},{});
var data =
[
{
"id": 1,
"status": "active",
"dataDetail": {
"id": 5,
"name": "tes 1",
"region": "aaa"
}
},
{
"id": 2,
"status": "active",
"dataDetail": {
"id": 8,
"name": "tes 2",
"region": "bbb"
}
},
{
"id": 3,
"status": "active",
"dataDetail": {
"id": 8,
"name": "tes 3",
"region": "aaa"
}
}
];
groups =_.chain(data).groupBy('dataDetail.region');
keys = groups.map( (value, key) => key);
values = groups.map( (value, key) => _.map(value, 'id'));
result = _.zipObject(keys, values);
I have a simple function below using which am trying create dynamic div containing a d3 chart for each row from the given input "json.res_full_sk"
However, when I use apply in Angularjs, am losing the historic data that is being assigned to dyndata object.
<script>
var app = angular.module('rpPlotExampleApp', ['ui.rpplot']);
app.controller('rpPlotCtrl', function ($scope) {
$scope.dyndata={};
$scope.assign_sk = function (testjsobj) {
alert('From Angular JS'+ JSON.stringify(testjsobj));
$scope.dyndata=testjsobj;
};
});
</script>
<script type="text/javascript">
jsonList = [];
jsonList.res_full_sk = [
{ "tid": 20, "sk": [{ "name": "Banking", "value": 40, "id": 0 }, { "name": "Housing", "value": 4, "id": 1 }, { "name": "Home", "value": 4, "id": 2 }, { "name": "NET", "value": 4, "id": 3 }] },
{ "tid": 22, "sk": [{ "name": "Movie", "value": 12, "id": 0 }, { "name": "Movie2", "value": 4, "id": 1 }, { "name": "Housing", "value": 4, "id": 2 }, { "name": "Banking", "value": 4, "id": 3 }, { "name": "C", "value": 4, "id": 4 }] },
{ "tid": 24, "sk": [{ "name": "Housing", "value": 4, "id": 0 }, { "name": "Home", "value": 4, "id": 1 }, { "name": "Banking", "value": 4, "id": 2 }] }
];
arr = [];
function getObjContents(i) {
arr = $.grep(jsonList.res_full_sk, function (e) {
return e.tid == i;
});
var str = "";
for (var i = 0; i < arr[0].sk.length; i++) {
str += ","+ JSON.stringify(arr[0].sk[i]);
}
str=str.substring(1);
str = "[" + str + "]";
str_obj=JSON.parse(str);
str_fin = {};
str_obj.forEach(function (e, i) {
str_fin['d' + i] = e;
});
return str_fin;
}
function insertDiv(Num) {
array = [];
var ar1 = Num.replace('[', '');
array = JSON.parse("[" + ar1 + "]");
var i = 0;
for (i; i < array.length; i++) {
js_data={};
js_data=getObjContents(array[i]);
testjsobj=js_data;
var scope = angular.element(document.getElementById("rpPlotCtrl")).scope();
scope.$watch("dyndata", function (oldval, newval) {
}, true);
scope.$apply(function () {
scope.dyndata = js_data;
});
var id_num;
id_num = array[i];
var rChart = angular.element(document.getElementById("sktemp"));
rChart.injector().invoke(function ($compile) {
$('<div obj></div>').insertAfter("#sktemp")
var obj = $('[obj]'); // get wrapper
var scope1 = $('[obj]').scope();
// generate dynamic content
alert(JSON.stringify(scope1.dyndata));
obj.html("<div class='skpro' id='skpro" + id_num + "' name='cn'><div class='skprovis' id='skprovis" + id_num + "' >Hello " + id_num + "<div class='half-plot' style='height:95%;width:95%;margin-top:0px;margin-left:5px;'><rp-plot dsn='dyndata' point-radius='1.5' scale='log' labelled='true' class='plot-rp-plot'></rp-plot></div></div></div>");
// compile!!!
console.log(obj.contents());
$compile(obj.contents())(scope1);
scope1.$apply();
});
}
}
</script>
The problem is dyndata is being changed for each value of i in the for loop, and thus the d3 chart is updated with the lastly assigned dyndata object.
As I see the dyndata object is being assigned with different values each time for loop executes, but it is not remaining but changes with the next value of dyndata to all the charts that were created.
How can I get the historic data to persist for dyndata that is already rendered for each for loop execution?
Am new to Angularjs and not very sure how I can make use of Angular.copy() for this scenario.
Problem seems to be with below code -
var scope = angular.element(document.getElementById("rpPlotCtrl")).scope();
scope.$watch("dyndata", function (oldval, newval) {
}, true);
scope.$apply(function () {
scope.dyndata = js_data;
});
as soon as I assign new js_data value to dyndata, all the existing charts gets updated with new value.
I tried using angular.copy(scope.dyndata)=js_data.. But it didn't work out.
Can you please suggest me?
Actually I need to show the data in an Array in this format after form validation. Please anyone help me out I'm new to angular js.
$scope.newuser=[
{
"EmployeeID": "A123",
"FullName": "phantommm",
"UserRegistrationDate": "2015-07-10T00:00:00",
"LastActiveDate": "2015-07-10T00:00:00",
"UserProjects": [
{
"UserID": 1,
"ProjectID": 1,
"ProjectRoleID": 2,
"IsAccepted": true
},
{
"UserID": 1,
"ProjectID": 2,
"ProjectRoleID": 3,
"IsAccepted": true
}
]
},
{
"EmployeeID": "A123",
"FullName": "phantommm",
"UserRegistrationDate": "2015-07-10T00:00:00",
"LastActiveDate": "2015-07-10T00:00:00",
"UserProjects": [
{
"UserID": 2,
"ProjectID": 1,
"ProjectRoleID": 2,
"IsAccepted": true
}
]
}
]
But i'm getting the data in this format,
$scope.newuser=[
{
"EmployeeID": "A123",
"FullName": "phantommm",
"UserRegistrationDate": "2015-07-10T00:00:00",
"LastActiveDate": "2015-07-10T00:00:00",
"UserID": 1,
"ProjectID": 1,
"ProjectRoleID": 2,
"IsAccepted": true
},
{
"EmployeeID": "A12345",
"FullName": "phantommm123",
"UserRegistrationDate": "2015-07-10T00:00:00",
"LastActiveDate": "2015-07-10T00:00:00",
"UserID": 2,
"ProjectID": 1,
"ProjectRoleID": 3,
"IsAccepted": true
}
]
I'm Using this code for getting the data from form,
myapp.controller('mainController', function ($scope) {
$scope.submitForm = function() {
$scope.newuser = [];
$scope.submitted = true;
$scope.counter = 1;
$scope.counter++;
if ($scope.userForm.$valid) {
$scope.newuser.push({
UserID : $scope.counter,
EmployeeID : $scope.user.employeeid,
FullName : $scope.user.fname,
UserPassword : $scope.user.confirmPassword,
EmailID : $scope.user.email,
Mobile : $scope.user.phone,
SecurityQuestionID : $scope.user.secutyqquestn,
SecurityAnswer : $scope.user.secutyanswer,
id : $scope.counter,
ctpjct : $scope.user.curntpjct,
pos : $scope.user.positio
})
alert('Registration Succesfully Completed');
} else {
alert('Invalid Fields')
}
};
});
I want to create a treeview array for use in Angular UI Tree. I want to create the structure from a array of object like this:
0: Object
body: null
categoryDescription: null
categoryTopic: null
description: null
faqBodyId: 0
faqCategoryId: 0
faqGroupId: 1
groupDescription: null
groupName: "Generelt"
groupTopic: "Generelt"
themeCode: "GEN"
topic: null
1: Object body: null categoryDescription: "Test af kategori" categoryTopic: "Mail" description: null faqBodyId: 0 faqCategoryId: 2 faqGroupId: 1 groupDescription: null groupName: null groupTopic: null themeCode: null topic: null
2: Object body: "This is a test" categoryDescription: null categoryTopic: null description: "Testing" faqBodyId: 3 faqCategoryId: 2 faqGroupId: 0 groupDescription: null groupName: null groupTopic: null themeCode: null topic: "Test123"
etc...
It is in three levels. Group, Category and Body
A node does not allways have a child!
I want It in this structure and three levels:
[
{
"id": 1,
"title": "1. dragon-breath",
"items": []
},
{
"id": 2,
"title": "2. moiré-vision",
"items": [
{
"id": 21,
"title": "2.1. tofu-animation",
"items": [
{
"id": 211,
"title": "2.1.1. spooky-giraffe",
"items": []
},
{
"id": 212,
"title": "2.1.2. bubble-burst",
"items": []
}
]
},
{
"id": 22,
"title": "2.2. barehand-atomsplitting",
"items": []
}
]
},
{
"id": 3,
"title": "3. unicorn-zapper",
"items": []
},
{
"id": 4,
"title": "4. romantic-transclusion",
"items": []
}
]
Structure
How is that done with Angular code?
I solved the problem like this.
The input array is sorted:
function buildtree(arr) {
var group = [];
angular.forEach(arr, function (value, index) {
if (value.faqGroupId > 0 && value.faqCategoryId == 0 && value.faqBodyId == 0) {
var category = [];
var faqgroup = {
"id": value.faqGroupId,
"title": value.groupTopic,
"description": value.groupDescription,
"name": value.groupName,
"items": category
}
angular.forEach(arr, function (valuecat, index) {
if (value.faqGroupId == valuecat.faqGroupId && valuecat.faqCategoryId > 0 && valuecat.faqBodyId == 0) {
var body = [];
var faqcat = {
"id": valuecat.faqCategoryId,
"title": valuecat.categoryTopic,
"description": valuecat.categoryDescription,
"items": body
}
angular.forEach(arr, function (valuebod, index) {
if (valuecat.faqGroupId == valuebod.faqGroupId && valuecat.faqCategoryId == valuebod.faqCategoryId && valuebod.faqBodyId > 0) {
var faqbody = {
"id": valuebod.faqBodyId,
"title": valuebod.topic,
"description": valuebod.description,
"body": valuebod.body,
}
body.push(faqbody);
}
})
category.push(faqcat);
}
})
group.push(faqgroup);
}
});
return group;
}
Array list :
Flat object array list
var dataList= [
{'id':1 ,'parentid' : 0, 'label'="label 1"},
{'id':4 ,'parentid' : 2 ,'label'="label 2"},
{'id':3 ,'parentid' : 1, 'label'="label 3"},
{'id':5 ,'parentid' : 0, 'label'="label 4"},
{'id':6 ,'parentid' : 0, 'label'="label 5"},
{'id':2 ,'parentid' : 1, 'label'="label 6"},
{'id':7 ,'parentid' : 4, 'label'="label 7"},
{'id':8 ,'parentid' : 1, 'label'="label 8"}
];
covert flat object array list to treeview list
function flatListToTreeViewData(dataList) {
var tree = [],
mappedArr = {},
arrElem,
mappedElem;
for (var i = 0, len = dataList.length; i < len; i++) {
arrElem = dataList[i];
mappedArr[arrElem.id] = arrElem;
mappedArr[arrElem.id]['children'] = [];
}
for (var id in mappedArr) {
if (mappedArr.hasOwnProperty(id)) {
mappedElem = mappedArr[id];
array of children.
if (mappedElem.parentID) {
mappedArr[mappedElem['parentID']]['children'].push(mappedElem);
}else {
tree.push(mappedElem);
}
}
}
return tree;
}