I am working on Rails 6 API. This is what I get
"data": [
{
"invoice_details": {
"customer_name": "Dylan Sollfrank",
"invoice_number": "1060",
"invoice_status": "paid"
}
},
{
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
},
Following is my code
def get_payment_report_activity(invoice_transactions, timezone = Time.zone.name)
invoice_details = []
transaction_details = {}
amount = {}
invoice_transactions.group_by(&:paymentable_id).each do |key, transactions|
invoice = Invoice.find key
invoice_details.push(invoice_details:{
customer_name: invoice&.customer&.fully_qualified_name&.strip,
invoice_number: invoice&.doc_number,
invoice_status: invoice&.invoice_status
})
transactions.each do |transaction|
customer = transaction&.paymentable&.customer
amount[:amount_to_pay] = transaction&.amount_to_pay.to_f
amount[:payment_fee] = transaction&.payment_fee.to_f
transaction_details[:transaction_number] = transaction&.transaction_number
transaction_details[:customer_name] = customer&.fully_qualified_name&.strip
transaction_details[:amount] = amount
transaction_details[:created_time] = Customer.time_format(transaction.created_at.in_time_zone(timezone))
transaction_details[:created_date] = Customer.date_format(transaction.created_at.in_time_zone(timezone))
transaction_details[:payment_method] = transaction&.payment_method
transaction_details[:payment_status] = transaction&.payment_status
end
invoice_details << transaction_details
end
invoice_details
end
Now I need the hash transaction details inside the invoice_details hash label as transaction_details and there can be multiple transaction details inside the invoice_details
"data": [
{
"invoice_details": {
"customer_name": "Dylan Sollfrank",
"invoice_number": "1060",
"invoice_status": "paid",
"transaction_details: [{
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
},
{
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
}]
},
"invoice_details": {
"customer_name": "Dylan Sollfrank",
"invoice_number": "1060",
"invoice_status": "paid",
"transaction_details : {
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
}
},
}
you can try like this:
def get_payment_report_activity(invoice_transactions, timezone = Time.zone.name)
invoice_details = []
invoice_transactions.group_by(&:paymentable_id).each do |key, transactions|
invoice = Invoice.find key
transaction_details = []
transactions.each do |transaction|
transaction_hash = {}
amount_hash = {}
customer = transaction&.paymentable&.customer
amount_hash[:amount_to_pay] = transaction&.amount_to_pay.to_f
amount_hash[:payment_fee] = transaction&.payment_fee.to_f
transaction_hash[:transaction_number] = transaction&.transaction_number
transaction_hash[:customer_name] = customer&.fully_qualified_name&.strip
transaction_hash[:created_time] = Customer.time_format(transaction.created_at.in_time_zone(timezone))
transaction_hash[:created_date] = Customer.date_format(transaction.created_at.in_time_zone(timezone))
transaction_hash[:payment_method] = transaction&.payment_method
transaction_hash[:payment_status] = transaction&.payment_status
transaction_hash[:amount] = amount_hash
transaction_details << transaction_hash
end
invoice_details.push(invoice_details: {
customer_name: invoice&.customer&.fully_qualified_name&.strip,
invoice_number: invoice&.doc_number,
invoice_status: invoice&.invoice_status,
transaction_details: transaction_details
})
end
invoice_details
end
Related
i'm new to Javascript and have sample set of array
[
{
"masterId": 56,
"type": "Alcohol Use",
"question": "Briefly describe any alcohol use - e.g. how many drinks a week?",
"answer": "5 alcohol consumed in a week"
},
{
"masterId": 57,
"type": "Allergies",
"questio": "Please list any allergies to medications or food.",
"answer": "Skin"
},
{
"masterId": 56,
"type": "Alcohol Use",
"questionn": "Which brand?",
"answer": "indian Monk"
}
]
basically i need to filter and convert this array based on masterId
This is an output which im expecting
[
{
"key": "Alchohol Use",
"value": [
{
"question": "Briefly describe any alcohol use - e.g. how many drinks a week?",
"answer": "5 alcohol consumed in a week"
},
{
"question": "Which brand?",
"answer": "indian Monk"
}
]
},
{
"key": "Allergies",
"value": [
{
"question": "Please list any allergies to medications or food",
"answer": "Skin"
}
]
}
]
im new to Javascript and aware of filter() method, but i can't develop a logic for above mentioned format.
let listOfQuestions = [{
"questionaireMasterId": 56,
"questionaireType": "Alcohol Use",
"questionnaireName": "Briefly describe any alcohol use - e.g. how many drinks a week?",
"questionaireAnswer": "5 alcohol consumed in a week"
},
{
"questionaireMasterId": 57,
"questionaireType": "Allergies",
"questionnaireName": "Please list any allergies to medications or food.",
"questionaireAnswer": "Skin"
},
{
"questionaireMasterId": 56,
"questionaireType": "Alcohol Use",
"questionnaireName": "Which brand?",
"questionaireAnswer": "indian Monk"
}
];
let questionaireTypeArray = [];
for (let i = 0; i < listOfQuestions.length; i++) {
questionaireTypeArray.push(listOfQuestions[i]['questionaireType']);
}
questionaireTypeArray = [...new Set(questionaireTypeArray)];
let finalArray = [];
for (let i = 0; i < questionaireTypeArray.length; i++) {
finalArray.push({
key: questionaireTypeArray[i],
value: [],
});
}
for (let i = 0; i < listOfQuestions.length; i++) {
for (let j = 0; j < finalArray.length; j++) {
if (finalArray[j]["key"] == listOfQuestions[i]["questionaireType"]) {
finalArray[j]["value"].push({
"question": listOfQuestions[i]["questionnaireName"],
"answer": listOfQuestions[i]["questionaireAnswer"],
});
}
}
}
console.log("Welcome to Programiz!", finalArray);
sample json data is this:
{
"variations": [
{
"variation_id": 391,
"name": "Fruit Shake - Chocolate, S",
"price": 10,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Chocolate"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "S"
}
]
},
{
"variation_id": 385,
"name": "Fruit Shake - Banana, L",
"price": 18,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Banana"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "L"
}
]
},
{
"variation_id": 386,
"name": "Fruit Shake - Banana, M",
"price": 15,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Banana"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "M"
}
]
}
]
}
my problem is, getting the variation_id where 2 or more attributes matches the array of string.
for example, chosenProduct = ["Banana", "L"]
I tried filter and contains but theres no way to match the other item from chosenProduct.
If I added the next condition, it returns nil
You can try this:
let varID = product.variations?.filter { att in
var matchedAttributes = 0
for thisAttribute in att.attribute {
if chosenProduct.contains(where: {$0 == thisAttribute.option}) {
matchedAttributes += 1
}
}
if matchedAttributes >= 2 {
return true
}
return false
}
Let me know if there's any doubt.
You can try this :
var chosenProduct = ["Banana","L"]
var expectedIds : [Int] = [Int]()
datas.variations?.map{ val in
val.attribute.map({ val2 in
let filtered = val2.enumerated().filter({chosenProduct.contains($0.element.option!)})
if filtered.count == chosenProduct.count{
expectedIds.append(val.variation_id!)
}
})
}
print(expectedIds) // [385]
I put the id's in array because of if you want to change your chosenProcudt example "Banana" (count 1 ). This mapping must be return variation_id like [385,386]
You can a method to Variation to make things easier:
extension Variation {
func attributesMatching(options: [String]) -> [Attribute] {
attribute.filter { options.contains($0.option) }
}
}
Then, you can just write:
let filtered = product.variations.filter { $0.attributesMatching(options: chosenProductOptions).count >= 2 }
print(filtered.map { $0.variationID })
I have fetched data from a JSON file.. But when I tried to fetch another data from it, am unable to do so as it is a nested array... I know the solution can arrive easily but this is the first time am trying to loop a JSON file.. so kindly give your inputs.
SampleData = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Immortality",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
};
GetJsonData() {
console.log(this.SampleData["powers"]);
for (let i = 0; i < this.SampleData["powers"].length; i++) {
if (this.SampleData["powers"][i].Immortality) {
console.log(this.SampleData.powers[i]);
}
}
}
{name: "Molecule Man", age: 29, secretIdentity: "Dan Jukes", powers: Array(3)}
{name: "Eternal Flame", age: 1000, secretIdentity: "Unknown", powers: Array(3)}
Your code needs to follow the structure of the JSON data; in particular, these are all valid things you could print:
console.log(this.SampleData.squadName);
console.log(this.SampleData.homeTown);
console.log(this.SampleData.members[0].name);
console.log(this.SampleData.members[0].powers[0]);
If you wanted to loop through each member and print their info, that might look like this:
this.SampleData.members.forEach(member => {
let powerString = member.powers.join(', ');
console.log('Name: ' + member.name);
console.log('Age: ' + member.age);
console.log('Powers: ' + powerString);
});
I used a forEach, but you can also use a for (let i = loop.
I have JSON input data as
{
"type": "insert",
"timestamp": 1536959101000,
"binlog_filename": "mysql-bin-changelog.234234",
"binlog_position": 223,
"database": "test",
"table_name": "demo",
"table_id": 138,
"columns": [
{
"id": 1,
"name": "id",
"column_type": 12,
"value": "IboECKV "
},
{
"id": 2,
"name": "col2",
"column_type": 93,
"value": "Fri Sep 14 21:05:02 UTC 2018"
},
{
"id": 3,
"name": "col3",
"column_type": 4,
"value": 10
},
{
"id": 4,
"name": "col4",
"column_type": 4,
"value": 0
}
]
}
If column_type =93 (datetime): convert value to : yyyy-MM-dd HH:mm:ss.SSSZ
So the the target out put is
[
{
"id": "IboECKV "
},
{
"col2": "2018-09-14 21:05:02.000Z"
},
{
"col3": 10
},
{
"col4": 0
}
]
Do you know how to solved that case?
Many thanks,
You can use ExecuteScript and leverage Groovy to do the parsing of Json input and the date and format it to however format you want using SimpleDateFormat.
A quick example:
import java.text.SimpleDateFormat
import java.util.Date
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import org.apache.commons.io.IOUtils
import java.nio.charset.StandardCharsets
flowFile = session.get()
if(!flowFile)return
def text = ''
session.read(flowFile, {inputStream ->
text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
} as InputStreamCallback)
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(text)
def columnsSize = object.columns.size
0.upto(columnsSize - 1) {
if (object.columns[it].column_type == 93 ) {
oldDate = object.columns[it].value
sdfmt2= new SimpleDateFormat('dd-M-yyyy')
parsedDate = sdfmt2.parse(oldDate)
object.columns[it].value = parsedDate
output = JsonOutput.toJson(object)
flowFile = session.write(flowFile, {outputStream ->
outputStream.write(output.getBytes(StandardCharsets.UTF_8))
} as OutputStreamCallback)
session.transfer(flowFile, REL_SUCCESS)
}
}
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;
}