Angular - Convert objects in a nested array into comma seapared values before binding to grid - arrays

below is part of my JSON response coming from an API
{
"totalCount": 2,
"customAttributes": [
{
"objectType": "OWNER",
"atrributeId": 215,
"attributeName": "DATELICENSEFIRSTISSUED",
"attributeDisplayName": "DATE LICENSE FIRST ISSUED",
"dataType": "DATE",
"inputValues": [],
"isGridEligible": "true",
"isInvoiceEligible": "false"
},
{
"objectType": "LOCATION",
"atrributeId": 217,
"attributeName": "DONOTRENEW",
"attributeDisplayName": "DO NOT RENEWS",
"dataType": "Value List",
"inputValues": [
{
"id": 5,
"value": "VEHICLELISTREQUIRED"
},
{
"id": 6,
"value": "STATESWITHRECIPROCITY"
}
],
"isGridEligible": "true",
"isInvoiceEligible": "false"
}
]
}
Here, I am binding customAttributes as grid data.
this.customFieldsService.getCustomFields(this.columnList, this.pageNumber, this.pageSize, null).subscribe(res => {
if(res){
this.cfData = res;
this.gridData = {
data: this.cfData.customAttributes,
total: this.cfData.totalCount
}
}
});
Here, my problem is with inputValues column, which comes as an array of objects. I need to convert it to comma seaparated values and then bind to grid data like
"inputValues": ["VEHICLELISTREQUIRED" "STATESWITHRECIPROCITY"]
I can ignore the "id" property as we are not using it at angular side. I tried using join method but not able to solve it within the nested array. Please suggest. Thanks.

In typescript it can be done with:
const joined: string = customAttribute.inputValues
.map(x => x.value) // [{value: 'VEHICLELISTREQUIRED'}, {value: 'STATESWITHRECIPROCITY'}]
.join(' ') // "VEHICLELISTREQUIRED" "STATESWITHRECIPROCITY"
const putIntoArray = [joined]; // ["VEHICLELISTREQUIRED" "STATESWITHRECIPROCITY"]
Of course you can put the joined string immediately into an array.

Related

How filter and delete object with null or empty property in json query

I have this json :
{
"meta": {
"status": 200,
"pagination": {
"page": 1,
"perPage": 15,
"hasNext": true
}
},
"data": [
{
"id": "1",
"title": "Movie title1"
"rating": null,
"playProviders": [
]
},
{
"id": "2",
"title": "Movie title2"
"rating": {
"ratingAssessment": "7.1"
},
"playProviders": [
"HBO", "Netflix"
]
},
....
}
I want to create a page with a list of movies, I need to fetch movies but only those which have a rating and playProviders, what parameters should I use in this request?
https://api.com/movies?orderBy=views
When I filters in the code:
programs.filter((program) => program.rating !== null);
it only gets a few films per page, those that don't have null. For example, 15 are per page and I get 2. How do I filter this? (I am using react typescript)
I don't have access to the API code. I need to filter what is returned by the API or write a query so that you get already filtered data from the API.
programs = [
{rating: 1,
playProviders: ["sf"]
},
{
rating: 4,
playProviders: []
}
]
programs.filter(function(program) {
if (program.rating !== null && program.playProviders.length !== 0) {
return program;
}
})

How to Join Multiple Arrays inside filter function of Arrays in Typescript

I am using Typescript in an Angular/Ionic project. I have an array of users that contain an array of skills. I have to filter users based on their online status as well as skills.
[
{
"id": 1,
"name": "Vikram Shah",
"online_status": "Online",
"skills": [{
"id": 2,
"title": "CSS"
},
{
"id": 3,
"title": "JavaScript"
},
{
"id": 4,
"title": "Python"
}
]
},
{
"id": 1,
"name": "Abhay Singh",
"online_status": "Online",
"skills": [{
"id": 1,
"title": "HTML"
},
{
"id": 2,
"title": "CSS"
},
{
"id": 3,
"title": "JavaScript"
},
{
"id": 4,
"title": "Python"
}
]
},
{
"id": 1,
"name": "Test Oberoi",
"online_status": "Online",
"skills": [{
"id": 1,
"title": "HTML"
},
{
"id": 2,
"title": "CSS"
},
{
"id": 3,
"title": "JavaScript"
},
{
"id": 4,
"title": "Python"
}
]
}
]
This is how all skills look like
this.skill_types = [
{"id":8,"title":"Cleaner", checked:false},
{"id":7,"title":"Painter", checked:false},
{"id":6,"title":"Plumber", checked:false},
{"id":5,"title":"Carpenter", checked:false},
{"id":4,"title":"Advisor", checked:false},
{"id":3,"title":"Team Leader", checked:false},
{"id":2,"title":"Management", checked:false},
{"id":1,"title":"Administrator", checked:false}
];
This array contains the IDs of skills that I want to filter
filterArr = [1, 3, 6];
This solution is almost working as expected. It is filtering well based on two criteria together.But not sure how to add condition for second filtering. The second filter should apply only if filterArr is not empty.
return this.items = this.items.filter((thisUser) => {
return thisUser.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1 &&
thisUser.skills.some(c => this.filterArr.includes(c.id))
});
The issue I am facing with code above is When there is no skill selected in the filter criteria, I would like to display all users. But it is not working that way. The logic here is to not apply any filter when the size of selected skills (filter condition) is greater than zero. So I tried this way....which looks similar to the way above...but this makes everything worse.
let filteredByStatus = [];
filteredByStatus = this.items.filter((thisUser) => {
return thisUser.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1
});
//Condition can be applied if filtering is separated
let filteredBySkills = [];
filteredBySkills = this.items.filter((thisUser) => {
return thisUser.skills.some(c => this.filterArr.includes(c.id))
});
//Expecting to join results from multiple filters
return this.items = filteredByStatus.concat(filteredBySkills);
But this is not working at all. Not sure what wrong is there. I am looking for a solution that enables to join arrays of similar objects without duplicating them.
Don't think you need to join arrays for your filtering. You can use something like rxjs filter.
return from(this.items)
.pipe(
filter(user => {
return user.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1
&& user.skills.some(c => filterArr.includes(c.id));
})
);
Or if you like to split it up you can just change it to like:
return from(this.items)
.pipe(
filter(user => user.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1),
filter(user => user.skills.some(c => filterArr.includes(c.id)))
);
Stackblitz: https://stackblitz.com/edit/angular-pk3w8b
You can tweak your condition a bit and place !this.filterArr.length in your condition (in terms of OR condition AND with user status) to make your whole condition gets true so that user gets filter.

How to modify a complex JSON Object in using Immutable

I have below JSON and wanted to update the value depending on Aid, Bid and Cid using Immutable.js
e.g.
Below input provided.
Aid= A, Bid = 1, Cid= 4, NewValue = 'FOUR'
If above input is provided the value "One" needs to be changed to "FOUR"
let sampleJson = {
Aid: 'A', detail:"sample", list: [
{
"Bid": "1",
"group": [
{
"name": "Group A",
"Cid": "4",
"value": "One"
},
{
"name": "Group A",
"Cid": "41",
"value": "1"
},
]
},
{
"Bid": "2",
"group": [
{
"name": "Group A",
"Cid": "4",
"value": "1"
},
{
"name": "Group A",
"Cid": "4",
"value": "1"
},
]
};
I was able to access the value using below code. How can i return the entire JSON with updated value?
let variale = Immutable.fromJS(sampleJson).
getIn(['list']).
find(allocation => allocation.get("Bid") === "1").
getIn(['group']).
find(fun => fun.get("Cid") === "4").set('value',"FOUR");
Anyone has any suggestions on how to resolve this problem?
I think you can try to do this like so:
let immutable = Immutable.fromJS(sampleJson);
immutable = immutable.setIn(['list', 0, 'group', 0, 'value'], 'FOUR');
This monstrosity is how I would do it:
const newData = originalData.update('list', list => {
const itemIndex = list.findIndex(item => item.get('Bid') === '2');
return list.update(itemIndex, listItem => {
return listItem.update('group', groupList => {
const groupIndex = list.findIndex(group => group.get('Cid') === '4');
return groupList.update(groupIndex, group => {
return group.set('value', 'FOUR');
});
});
});
});
https://jsbin.com/latupo/7/edit?html,js,console
Personally I stopped using Immutable, I always found it a bit painful (not to mention those docs!). I now use redux and good old cloning to not mutate state. Less performant in theory but if you've got nothing that runs over a few milliseconds anyway, save yourself the trouble...

How to filter following JSON with ionic filter bar

Using Ionic Filter Bar for implementing search in ionic app, I need to to search on "parent_type" and "child_type" from following json,
{
"status": {
"code": 200,
"message": "all data grabbed successfully",
"cause": ""
},
"ParentData": [
{
"id": 67,
"parent_type": "Parent Type",
"child": [
{
"id": 86,
"child_type": "Child Type"
},
{
"id": 93,
"child_type": "Child Type1"
}
]
},
{
"id": 68,
"parent_type": "Parent Type 1",
"child": [
{
"id": 87,
"child_type": "Child Type 1"
},
{
"id": 94,
"child_type": "Child Type 2"
}
]
}
]
}
its working fine for "parent_type" with following code
Here is the filter code
$scope.showFilterBar = function () {
filterBarInstance = $ionicFilterBar.show({
//setting parentData in following way after rest service call
//$scope.parentData = jsondata.ParentData
items: $scope.parentData,
update: function (filteredItems, filterText) {
$scope.parentData = filteredItems;
if (filterText) {
console.log(filterText);
}
},
filterProperties: ['parent_type']
});
};
But not able to search on "child_type"
So is there any way to set filterProperties so it will work for both "parent_type" and "child_type" or any other way to search this Json?
Thanks.
You should remove the "filterProperties" key and then add "expression" key.
Your "filterBarInstance" will be something like this:
$scope.showFilterBar = function () {
filterBarInstance = $ionicFilterBar.show({
items: $scope.parentData,
update: function (filteredItems, filterText) {
$scope.parentData = filteredItems;
if (filterText) {
console.log(filterText);
}
},
expression: function(filterText,value,index,array){
// This function is called for every ParentData object.
// "value" will be the current ParentData object,
// you'll need to iterate over all the "child" array in order to
// check if any of the "child_type" keys contains the "filterText"
// so if "parent_type" contains the "filterText" and any(? or all)
// of the the "child[x].child_type" values also contains the
// "filterText" return true
}
});
};
Check https://github.com/djett41/ionic-filter-bar for the original documentation.
Sorry for my english :)

ForEach Loop JSON AngularJS Object in Object

I am very new to AngularJS and I am trying to learn how to get deeper into a JSON object that has objects inside of objects and sometimes even arrays. This is a "simplified" version I am working with and I hope it will help me get a basic understanding so I can do the rest on my own.
json
values = {
"profile": {
"fields": {
"number-of-fields": "700",
"inside": [
"test1",
"test2"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
}
code
angular.forEach(values, function(value, key) {
console.log(key + ': ' + value);
// I know I need to loop inside of each object I beleieve
});
http://jsfiddle.net/ygahqdge/184/
The basics
Traverse object properties with a dot ., traverse array indexes with an index reference, [0|1|2|etc.].
What about your object?
var yoObject = {
"profile": {
"fields": {
"number-of-fields": "700",
"inside": [
"test1",
"test2"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
}
Get the inside values:
// object object object array
yoObject.profile.fields.inside.map(console.log, console) // ["test1", "test2"]
Get the id:
// object property
yoObject.id // "12312312333645"
Get all properties of the fields object:
Object.keys(yoObject.profile.fields) // ['number-of-fields', 'inside', 'type', 'values']
Get all values of the properies from above:
fields = yoObject.profile.fields
Object.keys(fields).map(key => console.log(fields[key])) // ["700", ["test1", "test2"], "test", "450"] // Note: Order isn't guaranteed
Just play about with things. Throw the object in the console and start to manually traverse it. Then try to loop over things.
Have fun!
Note: I tested none of that! :P
this is a question in regards on the right way to loop deep in JSON
objects – #user2402107
There's no right way. Sometimes you'll need to be fully dynamic, other times you can hardcode paths into nested properties and values.
Fiddle-Diddle
Nest as many times as you need:
angular.forEach(values, (value, key) => {
console.log("Value for", key, ":", value);
angular.forEach(value, (value, key) => {
console.log("Value for", key, ":", value);
angular.forEach(value, (value, key) => {
console.log("Value for", key, ":", value);
})
})
});
You can log the whole object to console. By using F12 tool, you can browse the object in the browser.
console.log(objectName);
angular.forEach works on arrays. lets suppose you have an array of objects as this
var values = [{
"profile": {
"fields": {
"number-of-fields": "700",
"interpertation": [
"whenever this is ready"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
},
{
"profile": {
"fields": {
"number-of-fields": "700",
"interpertation": [
"whenever this is ready"
],
"type": "test",
"values": "450"
}
},
"id": "12312312333645"
}]
you can explore each object and its properties like this
angular.forEach(values, function(value, key) {
console.log(value.profile.fields.values);
});
you can use . notation to access propertes

Resources