How to filter JSON data based on another JSON data in typescript - reactjs

I have 2 JSON Data 1. Payers 2. Rules. I need to filter Payers JSON data based on PayerId from Rules JSON data.
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}}
Rules JSON file
{
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
}]}
I need to filter Payers JSON data based on Rules JSON data if PayerID matches
I need output like below
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "34567",
"name": "Test Payer3"
}
}
How to filter?

You can use Array.filter like that (based on your data structure):
const filteredPayers = payersObj.Payers.filter((p) => rulesObj.Rules[0].Criteria[0].payerId.includes(p.payerId));
I can't figure out why your Rules json looks like this, I guess you have multiple rules. If so, you will need to iterate over each rule and invoke includes. Same for Criteria.

Code will check each rule and each critirias
and will return payers if payerId found in any of the given rules of any criteria
const payers = {
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}]}
const rules = {
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
]
}
const data = payers.Payers.filter(payer => rules.Rules.findIndex(rule => rule.Criteria.findIndex(criteria => criteria.payerId.includes(payer.payerId)) != -1) !== -1)
console.log(data)

Related

Is it possible to get key value pairs from snowflake api instead rowType?

I'm working with an API from snowflake and to deal with the json data, I would need to receive data as key-value paired instead of rowType.
I've been searching for results but haven't found any
e.g. A table user with name and email attributes
Name
Email
Kelly
kelly#email.com
Fisher
fisher#email.com
I would request this body:
{
"statement": "SELECT * FROM user",
"timeout": 60,
"database": "DEV",
"schema": "PLACE",
"warehouse": "WH",
"role": "DEV_READER",
"bindings": {
"1": {
"type": "FIXED",
"value": "123"
}
}
}
The results would come like:
{
"resultSetMetaData": {
...
"rowType": [
{ "name": "Name",
...},
{ "name": "Email",
...}
],
},
"data": [
[
"Kelly",
"kelly#email.com"
],
[
"Fisher",
"fisher#email.com"
]
]
}
And the results needed would be:
{
"resultSetMetaData": {
...
"data": [
[
"Name":"Kelly",
"Email":"kelly#email.com"
],
[
"Name":"Fisher",
"Email":"fisher#email.com"
]
]
}
Thank you for any inputs
The output is not valid JSON, but the return can arrive in a slightly different format:
{
"resultSetMetaData": {
...
"data":
[
{
"Name": "Kelly",
"Email": "kelly#email.com"
},
{
"Name": "Fisher",
"Email": "fisher#email.com"
}
]
}
}
To get the API to send it that way, you can change the SQL from select * to:
select object_construct(*) as KVP from "USER";
You can also specify the names of the keys using:
select object_construct('NAME', "NAME", 'EMAIL', EMAIL) from "USER";
The object_construct function takes an arbitrary number of parameters, as long as they're even, so:
object_construct('KEY1', VALUE1, 'KEY2', VALUE2, <'KEY_N'>, <VALUE_N>)

How can i filter the un matched array elements alone when compare with another array objects in angular 8

I have a two array response and I would like to compare the two responses and have to filter the unmatched array elements into a new array object.
Condition to compare the two response and filter is: we have to filter when code and number are not matched exactly with the response two then we have to filter such an array element into a new array object which I need as an output.
The Array element present in the Response two example is also present in the Response of Array One example which I don't want and I need to filter the array elements which is not matched with the Response of Array One.
Final Output which we filtered from the response two array will be like below which is unmatched with the response 1 array object:
{
"unmatchedArrayRes": [
{
"code": "08",
"number": "2323232323",
"id": "432",
"value": "value432"
}
]
}
Response of Array One
{
"MainData": [
{
"DataResponseOne": [
{
"viewData": {
"number": "11111111111111",
"code": "01"
},
"name": "viewDataOne"
},
{
"viewData": {
"number": "22222222222222",
"code": "01"
},
"name": "viewDataTwo"
},
{
"viewData": {
"number": "3333333333333",
"code": "02"
},
"name": "viewDataThree"
}
]
},
{
"DataResponseTwo": [
{
"viewData": {
"number": "5555555555555",
"code": "9090"
},
"name": "viewDataFour"
},
{
"viewData": {
"number": "6666666666666",
"code": "01"
},
"name": "viewDataFive"
},
{
"viewData": {
"number": "8888888888888",
"code": "01"
},
"name": "viewDataSix"
}
]
}
]
}
Response Two Example :
{
"compareRes": [
{
"code": "01",
"number": "11111111111111",
"id": "123",
"value": "value123"
},
{
"code": "9090",
"number": "5555555555555",
"id": "345",
"value": "value567"
},
{
"code": "08",
"number": "2323232323",
"id": "432",
"value": "value432"
}
],
"metaData": "343434343434"
}
First, create a combined list of all the view items from response one.
const combinedList = [];
res1["MainData"].forEach(data => {
// console.log(data);
for( let key in data) {
// console.log(key);
data[key].forEach(innerData => {
console.log(innerData)
combinedList.push(innerData["viewData"]);
})
}
});
In the above method, It is done in such a way that it can handle multiple viewData responses like DataResponseOne, DataResponseTwo, and so on.
And then filter second response Items like this:
const unfilteredListItems = res2["compareRes"].filter(data => {
return !combinedList.some(listItem => {
return listItem.code === data.code && listItem.number === data.number;
});
});
console.log(unfilteredListItems);
Working Stackblitz link: https://stackblitz.com/edit/ngx-translate-example-aq1eik?file=src%2Fapp%2Fapp.component.html

Extended dimensions set doesn't return data

I want to pull a number of metrics from Google Analytics API with "Traffic Sources", "Geo Network" and "Audience" dimensions.
So I create the following request. GA Dimensions & Metrics Explorer shows that these metrics & dimensions are compatible. But for some reason, this request returns zero values:
{
"reportRequests": [
{
"viewId": "xxxxxxxx",
"dateRanges": [
{
"startDate": "2020-03-01",
"endDate": "2020-03-11"
}
],
"metrics": [
{
"expression": "ga:sessions"
},
{
"expression": "ga:newUsers"
},
{
"expression": "ga:transactions"
},
{
"expression": "ga:transactionRevenue"
}
],
"dimensions": [
{
"name": "ga:date"
},
{
"name": "ga:campaign"
},
{
"name": "ga:sourceMedium"
},
{
"name": "ga:country"
},
{
"name": "ga:region"
},
{
"name": "ga:city"
},
{
"name": "ga:userAgeBracket"
},
{
"name": "ga:userGender"
},
{
"name": "ga:interestInMarketCategory"
}
]
}
]
}
Although restricted dimensions set shows that data exists:
"dimensions": [
{
"name": "ga:date"
},
{
"name": "ga:campaign"
},
{
"name": "ga:sourceMedium"
},
{
"name": "ga:country"
},
{
"name": "ga:region"
},
{
"name": "ga:city"
}
Why extended dimensions set that shown in 1st example doesn't return data?
Thanks in advance!
Eugene
May be GA doesnot have any information about the user age, gender and in-Market segment (ga:interestInMarketCategory). So when you add these dimensions with others, API returns data for the combination of specified dimensions.
So let's say there are 20 sessions from combination of city = x and region = y. But when you add gender to it, no combination can be made (e.g. city = x and region = y and gender = ?), hence API will return zero response.

How to Update nested Array in RethinkDB using ReQL

I have a question on Updating the array in RethinkDB. My JSON structure looks like below.
{
"LOG_EVENT": {
"ATTRIBUTES": [
{
"ATTRIBUTE1": "TYPE",
"VALUE": "ORDER"
},
{
"ATTRIBUTE2": "NUMBER",
"VALUE": "1234567"
}
],
"EVENT_CODE": [
{
"CODE_NAME": "EVENT_SAVED",
"EVENT_TIMESTAMP": "2015-08-18T00:58:12.421+08:00"
}
],
"MSG_HEADER": {
"BUSINESS_OBJ_TYPE": "order",
"MSG_ID": "f79a672b-f15e-459d-a29b-725486d6401f",
"DESTINATIONS": "3"
}
},
"id": "0de3117e-12dd-4d10-a464-dff391a4513f"
}
Here, I am trying to Update a new event inside my event code
{
"CODE_NAME": "MESSAGE_DELIVERED_TO_APP2",
"EVENT_TIMESTAMP": "2015-08-18T12:58:12.421+08:00"
}
My final JSON will look like below,
{
"LOG_EVENT": {
"ATTRIBUTES": [
{
"ATTRIBUTE1": "TYPE",
"VALUE": "ORDER"
},
{
"ATTRIBUTE2": "NUMBER",
"VALUE": "1234567"
}
],
"EVENT_CODE": [
{
"CODE_NAME": "EVENT_SAVED",
"EVENT_TIMESTAMP": "2015-08-18T00:58:12.421+08:00"
},
{
"CODE_NAME": "MESSAGE_DELIVERED_TO_APP2",
"EVENT_TIMESTAMP": "2015-08-18T12:58:12.421+08:00"
}
],
"MSG_HEADER": {
"BUSINESS_OBJ_TYPE": "order",
"MSG_ID": "f79a672b-f15e-459d-a29b-725486d6401f",
"DESTINATIONS": "3"
}
},
"id": "0de3117e-12dd-4d10-a464-dff391a4513f"
}
Can you help on the ReQL query ?
Tried below, but not working
r.db("test").table("test1").get("0de3117e-12dd-4d10-a464-dff391a4513f")("LOG_EVENT")('EVENT_CODE').update(function(row) {
return {EVENT_CODE: row('EVENT_CODE').map(function(d) {
return r.branch(d.append({
"CODE_NAME": "MESSAGE_DELIVERED_TO_APP2",
"EVENT_TIMESTAMP": "2015-08-18T00:58:12.421+08:00"
}), d)
})
}} )
well here is the code which updates the nested fields of object residing inside an array
r.db('DB').table('LOGS')
.get('ID')
.update({
EVENT_CODE: r.row('EVENT_CODE')
.changeAt(1, r.row('EVENT_CODE').nth(1)
.merge({"CODE_NAME": "MESSAGE_DELIVERED_TO_APP2"}))
})

How to filter embedded array in mongo document with morphia

Given my Profile data looks like below, I want to find the profile for combination of userName and productId
and only return the profile with the respective contract for this product.
{
"firstName": "John",
"lastName": "Doe",
"userName": "john.doe#gmail.com",
"language": "NL",
"timeZone": "Europe/Amsterdam",
"contracts": [
{
"contractId": "DEMO1-CONTRACT",
"productId": "ticket-api",
"startDate": ISODate('2016-06-29T09:06:42.391Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "ticket",
"permission": "createTicket"
},
{
"activity": "ticket",
"permission": "updateTicket"
},
{
"activity": "ticket",
"permission": "closeTicket"
}
]
}
]
},
{
"contractId": "DEMO2-CONTRACT",
"productId": "comment-api",
"startDate": ISODate('2016-06-29T10:27:45.899Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "comment",
"permission": "createComment"
},
{
"activity": "comment",
"permission": "updateComment"
},
{
"activity": "comment",
"permission": "deleteComment"
}
]
}
]
}
]
}
I managed to find the solution how to do this from the command line. But I don't seem to find a way how to accomplish this with Morphia (latest version).
db.Profile.aggregate([
{ $match: {"userName": "john.doe#gmail.com"}},
{ $project: {
contracts: {$filter: {
input: '$contracts',
as: 'contract',
cond: {$eq: ['$$contract.productId', "ticket-api"]}
}}
}}
])
This is what I have so far. Any help is most appreciated
Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression(??))
Note... meanwhile I found another solution which does not use an aggregation pipeline.
public Optional<Profile> findByUserNameAndContractQuery(String userName, String productId) {
DBObject contractQuery = BasicDBObjectBuilder.start(Contract._productId, productId).get();
Query<Profile> query =
getDatastore()
.createQuery(Profile.class)
.field(Profile._userName).equal(userName)
.filter(Profile._contracts + " elem", contractQuery)
.retrievedFields(true, Profile._contracts + ".$");
return Optional.ofNullable(query.get());
}
I finally found the best way (under assumption I only want to return max. 1 element from array) to filter embedded array.
db.Profile.aggregate([
{ $match: {"userName": "john.doe#gmail.com"}},
{ $unwind: "$contracts"},
{ $match: {"contracts.productId": "comment-api"}}
])
To match according to your first design you could try the projection settings with morphia aggregation pipeline.
Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression("$filter", new BasicDBObject()
.append("input", "$contracts")
.append("as", "contract")
.append("cond", new BasicDBObject()
.append("$eq", Arrays.asList('$$contract.productId', "ticket-api")));
Also see the example written by the morphia crew around line 88 at https://github.com/mongodb/morphia/blob/master/morphia/src/test/java/org/mongodb/morphia/aggregation/AggregationTest.java.

Resources