accessing nested json array using angular - arrays

I am trying to access the nested tree view of child item from json array.I am facing difficulties in accessing multiple children from the below complex json,have been stuck with it for days....can anyone help me how to access all children using angular or through java script,Also how can i know that which children belong to which parent.I was only able to get the child of first parents by trying out the below code:
here the json is assigned to value=datasource.data;
this.dataSource.data.forEach((item,i)=>{
console.log(item.children);
if(item.children){
item.children.forEach((childItems,i)=>{
console.log(childItems);
})
}
Here is the json :
TREE_DATA: FoodNode[] =
[
{
name: 'Dashboard',
id: "0",
startButton: "enabled",
stopButton: "enabled",
type: "ec2",
children: [
{
name: 'Backend-Server',
id: "1",
startButton: "enabled",
stopButton: "enabled",
type: "ec2",
children: [
{
startButton: "disabled",
stopButton: "enabled",
type: "ec2",
name: 'Backend-Server-1',
id: "3"
},
{
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
name: 'Backend-Server-2',
id: "4"
},
]
},
{
startButton: "enabled",
stopButton: "disabled",
type: "rds",
name: 'Frontend-Server',
id: "5"
},
{
startButton: "enabled",
stopButton: "enabled",
type: "ec2",
name: 'Backup-Server',
id: "6"
},
]
},
{
name: 'Admin',
id: "7",
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
children: [
{
name: 'Backend-Server',
id: "8",
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
children: [
{
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
name: 'Backend-Server-1',
id: "9"
},
{
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
name: 'Backend-Server-2',
id: "10"
},
]
}, {
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
name: 'Frontend-Server',
id: "11",
children: [
{
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
name: 'Frontend-Server-1',
id: "12",
},
{
startButton: "enabled",
stopButton: "disabled",
type: "ec2",
name: 'Frontend-Server-3',
id: "13"
},
]
},
]
},
]

The json you have is a nested json.We need to call recursive function for it.The below solution might help your problem
var childItem=[];
function getChildren(data){
data.forEach((each)=>{
if(each.children){
getChildren(each.children);
}else{
childItem.push(each);
}
});
}
getChildren(this.dataSource.data);
console.log(childItem);

Since you have a tree structure of children You need to use recursion
const { data } = this.dataSource;
var children=[];
function getChildNodes(data){
data.forEach((child)=>{
child.children)? getChildNodes(child.children): childrens.push(child);
});
}
getChildNodes(data);
console.warn(children);

Related

I am struggling with managing the state of a react form

i have this json object which i use to map the form. I have a lot of nested questions. It is used for medical purposes. Here's an portion of the json
parts: [
{
title: "Surgery-related",
questions: [
{
type: "radio",
required: true,
label: "Timing of surgery",
name: "timing_of_surgery",
options: [
{
label: "Emergent non-cardiac surgery",
value: "emergent_non_cardiac_surgery",
},
{
label: "Urgent non-cardiac surgery",
value: "urgent_non_cardiac_surgery",
},
{
label: "Time-sensitive non-cardiac surgery",
value: "time_sensitive_non_cardiac_surgery",
},
{
label: "Elective non-cardiac surgery",
value: "elective_non_cardiac_surgery",
name: "elective_non_cardiac_surgery",
nestedQuestion: {
type: "radio",
options: [
{
label: "Possible to defer non-cardiac surgery",
value: "possible_to_defer_non_cardiac_surgery",
},
{
label: "Not possible to defer non-cardiac surgery",
value: "not_possible_to_defer_non_cardiac_surgery",
},
],
},
},
],
},
{
type: "select",
required: true,
label: "Type of surgery or intervention",
name: "type_of_surgery_or_intervention",
options: [
{
value: "Low surgical risk (<1%)",
titles: [
"Breast",
"Dental",
"Endocrine: thyroid",
"Eye",
"Gynaecological: minor",
"Orthopaedic minor (meniscectomy)",
"Reconstructive",
"Superficial surgery",
"Urological minor: (transurethral resection of the prostate)",
"Video assisted thoracic surgery minor lung resection",
],
},
{
value: "Intermediate surgical risk (1-5%)",
titles: [
"Carotid asymptomatic (coronary endarterectomy or coronary artery stenting)",
"Carotid symptomatic (coronary endarterectomy)",
"Endovascular aortic aneurysm repair",
"Head or neck surgery",
"Intraperitoneal: splenectomy, hiatal hernia repair, cholecystectomy",
"Intrathoracic: non-major",
"Neurological or orthopaedic: major (hip and spine surgery)",
"Peripheral arterial angioplasty",
"Renal transplants",
"Urological or gynaecological: major",
],
},
{
value: "High surgical risk (>5%)",
titles: [
"Adrenal resection",
"Aortic and major vascular surgery",
"Carotid symptomatic (Carotid artery stenting)",
"Duodenal-pancreatic surgery",
"Liver resection, bile duct surgery ",
"Oesophagectomy",
"Open lower limb revascularization for acute limb ischaemia or amputation",
"Pneumonectomy (video-assisted thoracic surgery or open surgery)",
"Pulmonary or liver transplant",
"Repair of perforated bowel",
"Total cystectomy",
],
},
],
},
{
type: "select",
required: true,
label: "Bleeding risk",
name: "bleeding_risk",
options: [
{
value: "Minor bleeding risk",
titles: [
"Cataract or glaucoma procedure",
"Dental procedures: extractions (1–3 teeth), periodontal surgery, implant positioning endodontic (root canal) procedures, subgingival scaling/cleaning",
"Endoscopy without biopsy or resection",
" Superficial surgery (e.g. abscess incision, small skin excisions/ biopsy)",
],
},
{
value: "Low bleeding risk",
titles: [
"Abdominal surgery: cholecystectomy, hernia repair, colon resection",
"Breast surgery",
"Complex dental procedures (multiple tooth extractions)",
"Endoscopy with simple biopsy",
"Gastroscopy or colonoscopy with simple biopsy",
"Large-bore needles procedures (e.g. bone marrow or lymph node biopsy)",
"Non-cataract ophthalmic surgery",
"Small orthopaedic surgery (foot, hand arthroscopy)",
],
},
{
value: "High bleeding risk",
titles: [
"Abdominal surgery with liver biopsy, extracorporeal shockwave lithotripsy",
"Extensive cancer surgery (e.g. pancreas, liver)",
"Neuraxial (spinal or epidural) anaesthesia",
"Neurosurgery (intracranial, spinal) ",
"Major orthopaedic surgery ",
"Procedures with vascular organ biopsy (kidney or prostate)",
"Reconstructive plastic surgery",
"Specific interventions (colon polypectomy, lumbar puncture, endovascular aneurysm repair)",
"Thoracic surgery, lung resection surgery",
" Urological surgery (prostatectomy, bladder tumour resection)",
"Vascular surgery (e.g. abdominal aortic aneuvrysm repair, vascular bypass)",
],
},
],
},
],
},
{
title: "Patient-related",
questions: [
{
type: "input",
input_type: "text",
placeholder: "Enter patient's name",
required: true,
label: "Patient's name",
name: "patient_name",
},
{
type: "checkbox",
required: false,
label: "Cardiovascular risk factor",
name: "cardiovascular_risk_factor",
options: [
{
label: "Hypertension",
value: "hypertension",
},
{
label: "Diabetes",
value: "diabetes",
},
{
label: "Dyslipidemia",
value: "dyslipidemia",
},
{
label: "Smoking",
value: "smoking",
},
{
label: "Age greater than or equal to 65 years",
value: "age_greater_than_65_years",
},
{
label: "Family history of cardiovascular disease",
value: "family_history_of_cardiovascular_disease",
required: true,
nestedQuestion: {
type: "checkbox",
options: [
{
label:
"Myocardial infarction or sudden death <55 years with father or brother",
value:
"myocardial_infarction_or_sudden_death_less_than_55_years_with_father_or_brother",
},
{
label:
"Myocardial infarction or sudden death <65 years with mother or sister",
value:
"myocardial_infarction_or_sudden_death_less_than_65_years_with_mother_or_sister",
},
{
label:
"Cerebrovascular accident <45 years with parents or brother/sister",
value:
"cerebrovascular_accident_less_than_45_years_with_parents_or_brother_sister",
},
],
},
},
],
},
{
type: "checkbox",
label: "Antecedents",
name: "antecedents",
sections: [
{
title: "Cardiovascular disease ",
options: [
{
label: "Heart failure",
value: "heart_failure",
namee: "heart_failure",
nestedQuestion: {
type: "radio",
options: [
{
label: "Stable heart failure",
value: "stable_heart_failure",
},
{
label: "Unstable heart failure",
value: "unstable_heart_failure",
},
],
},
},
{
label: "Coronary artery disease",
value: "coronary_artery_disease",
},
{
label: "Vasopastic angina",
value: "vasopastic_angina",
},
{
label: "Mechanical prosthetic valve",
value: "mechanical_prosthetic_valve",
name: "mechanical_prosthetic_valve",
nestedQuestion: {
type: "checkbox",
options: [
{
label:
"Mechanical aortic valve replacement(AVR), associated with ",
value:
"mechanical_aortic_valve_replacement_associated_with",
name: "mechanical_aortic_valve_replacement_associated_with",
nestedQuestion: {
type: "checkbox",
options: [
{
label: "Atrial fibrillation",
value: "atrial_fibrillation1",
},
{
label: "Previous thromboembolism, ",
value: "previous_thromboembolism",
},
{
label: "Severe left ventricular dysfunction ",
value: "severe_left_ventricular_dysfunction",
},
{
label: "Hypercoagulable state",
value: "hypercoagulable_state",
},
]
}
},
{
label:
"Older-generation mechanical aortic valve replacement ",
value:
"older_generation_mechanical_aortic_valve_replacement",
},
{
label: "Mechanical mitral valve replacement",
value: "mechanical_mitral_valve_replacement",
},
],
},
},
{
label: "Atrial fibrillation",
value: "atrial_fibrillation",
},
{
label: "Other rythmic antecedents",
value: "other_rythmic_antecedents",
},
{
label: "Venous thromboembolism",
value: "venous_thromboembolism",
},
],
},
{
title: "Non cardiovascular disease",
options: [
{
label: "Diabetes mellitus",
value: "diabetes_mellitus",
},
{
label: "Renal failure",
value: "renal_failure",
},
],
},
],
},
],
},
{
title: "Examination",
questions: [
{
type: "checkbox",
required: true,
label: "Examination",
name: "examination",
options: [
{
label: "Asymptomatic",
value: "asymptomatic",
default: true,
},
{
label: "Newly detected murmurs",
value: "newly_detected_murmurs",
},
{
label: "Chest pain",
value: "chest_pain",
},
{
label: "Symptoms/signs suggestive of cardio-vascular disease",
value: "symptoms_signs_suggestive_of_cardiovascular_disease",
},
{
label:
"Poor functional capacity (METs<4 –if the patient cannot climb two flights of stairs-)",
value: "poor_functional_capacity",
},
{
label: "High clinical risk factor : (RCRI >= 1)",
value: "high_clinical_risk_factor",
name: "high_clinical_risk_factor",
required: true,
nestedQuestion: {
type: "checkbox",
options: [
{
label: "Ischaemic heart disease",
value: "ischaemic_heart_disease",
},
{
label: "Cerebrovascular disease",
value: "cerebrovascular_disease",
},
{
label: "History of congestive heart failure",
value: "history_of_congestive_heart_failure",
},
{
label: "Insulin therapy for diabetes",
value: "insulin_therapy_for_diabetes",
},
{
label: "Serum creatinine level ≥2 mg/dL",
value:
"serum_creatinine_level_greater_than_or_equal_to_2_mg_per_dL",
},
{
label: "High-risk surgery",
value: "high_risk_surgery",
},
],
},
},
{
label: "Abnormal ECG",
value: "abnormal_ecg",
name: "abnormal_ecg",
required: true,
nestedQuestion: {
type: "checkbox",
options: [
{
label: "Pathological Q wave",
value: "pathological_q_wave",
},
{
label: "ST-T wave changes",
value: "st_t_wave_changes",
},
{
label: "Non-sinus rhythm",
value: "non_sinus_rhythm",
},
{
label: "Left bundle branch block",
value: "left_bundle_branch_block",
},
],
},
},
{
label: "High NT-pro-BNP/BNP",
value: "high_nt_pro_bnp_bnp",
},
{
label: "Acute coronary syndrome",
value: "acute_coronary_syndrome",
},
],
},
],
},
],
The way i render this form is using recursion. I have this jsx component named Question.jsx which i pass with it the question. Where i'm stuck is to manage the state of the hole form in one useState hook object. And espacialy when it comes to nested questions with levels of more the 2. As i need to update the parent. I realy need help please !

Difficulties to query nested arrays with multiple itens Mongoose

I`ve modeled a document to be:
let UserSchema = new Schema({
name: { type: String, required: true, max: 50, unique: true },
email: {type: String, required: true, max: 50, unique: true},
password: {type: String, required: true, max: 20},
monitoringProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
],
controlProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
]
});
In the monitoringProject, for example, I can log too many different projects, and, to each project, I can log too many dispositives. So, I have nested arrays. In other project, where I have just one project, and many dispositives, I can list them and search for just one dispositive. But in this case, like this:
[ { "_id": "5ee18ece1ea5af75bae55f91", "monitoringProject": [ { "dispositives": [ { "_id": "5ee18ef31ea5af75bae55f9c", "name": "Dispositivo 1", "token": "$2b$15$NntmY9ihNZ7R1Vg1WMtmzOSjlfCoKIuHLofF6g5tKXA57WLLc2At2" }, { "_id": "5ee18ef81ea5af75bae55f9e", "name": "Dispositivo 2", "token": "$2b$15$OZB7HbDLvonsv6A71ozW7.yVY2vJOipTCj0AH7XzoafQwwDho.jpm" }, { "_id": "5ee18efc1ea5af75bae55fa0", "name": "Dispositivo 3", "token": "$2b$15$0hpDzNeTO2qJzBVyAHc/UesrnIRi/YpeAlpCLewNhmfl6fe3SEN0i" }, { "_id": "5ee2278d0754817853134bf3", "name": "Dispositivo 4", "token": "$2b$15$ldC5/CyxITPJGUvtXJ.2S.D6a3FBftg6ctQeS4ne/9xpMP5PPiszK" }, { "_id": "5ee2288956fc4c7870044395", "name": "Dispositivo 6", "token": "$2b$15$3rJt.gXEi/gALvrwxVUsWuwF2RUcBmZcoFOQeXwF45ZuKQrB3AGHG" }, { "_id": "5ee6d23d1756b7a8384bcff0", "name": "Dispositivo 7", "token": "$2b$15$C3I9STKJpf9i/7hzhvHEs.IizXpOEmgRTD3hd7ZSdcvATb73Z0zNC" } ], "_id": "5ee18ede1ea5af75bae55f94", "projectName": "Projeto 2", "token": "$2b$15$xaytMbMnGd3BMAGapX8nn.imvkQKetqx0OIlUUyP3gCxlKz/G6DiG" } ] } ]
I can only list all the Dispositives. I want to return just, for example, "Dispositivo 2".
I used to querys:
await User.find({ email: req.body.email, monitoringProject: { $elemMatch: { token: req.body.projecttoken, dispositives: { $elemMatch: { token: req.body.dispositivetoken } } } } }, { "monitoringProject.$.dispositives": 1} )
or
await User.find({ email: req.body.email, 'monitoringProject.token': req.body.projecttoken, 'monitoringProject.dispositives.token': req.body.dispositivetoken}, { 'monitoringProject.dispositives.$': 1 })
Using find or findOne. How can I return just the document I want? I tried so many different ways, but with no lucky.

Object is undefined while have data

I have an array contains object look like below
[
{
_id: "12",
data: { _id: "123", isDelete: false, name: "afd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
},
{
_id: "12",
data: { _id: "123", isDelete: false, name: "ffd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
},
]
This is when I filter in it
brands.filter(brand => {
console.log(brand);// like above data
console.log(brand.data);// show brand.data
console.log(brand.data._id);//error brand.data is not defined
})
I already try
brands.filter(brand => {
let a = brand.data;
console.log(a._id);// error a is null
})
I need to get brand.data.name like when I loop it need to print afd and ffd.
As per your question if all you want to do is to log the value of brand.data.name then using filter doesn't make any sense.
You can just use forEach for that.
const brands = [
{
_id: "12",
data: { _id: "123", isDelete: false, name: "afd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
},
{
_id: "12",
data: { _id: "123", isDelete: false, name: "ffd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
}
];
brands.forEach(brand => { console.log(brand.data.name) });
If you want to store the names in an array instead of just logging them then you can use map for that.
const brands = [
{
_id: "12",
data: { _id: "123", isDelete: false, name: "afd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
},
{
_id: "12",
data: { _id: "123", isDelete: false, name: "ffd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
}
];
const brandNames = brands.map(brand => brand.data.name);
console.log(brandNames);
Javascript filter works on array. So considering you want to filter your nested object(based on id) which is data, your code should be written like below-
const brands = [
{
_id: "12",
data: { _id: "1", isDelete: false, name: "afd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
},
{
_id: "13",
data: { _id: "2", isDelete: false, name: "ffd" },
createdAt: "2020-04-11T08:38:15.966Z",
shop_id: "sfd",
updatedAt: "2020-04-27T02:07:12.271Z"
},
]
const updatedBrands = brands.map(brand => {(
...brand, brand.data.filter(key => key._id === '1')
}))
You have to first use javascript map method to iterate over the array and then you can filter your data object by id. Hope this helps.

Antd tree table grouped by column value

I need to implement tree table in my react application. that has grouped by an object property value.
The object is as follows
{
"SP": [
{
"DisplayName": "audi",
"Name": "r8",
"Type": "2012"
},
{
"DisplayName": "audi",
"Name": "rs5",
"Type": "2013"
}
],
"Code": [
{
"DisplayName": "ford",
"Name": "mustang",
"Type": "2012"
},
{
"DisplayName": "ford",
"Name": "fusion",
"Type": "2015"
}
],
"Message": [
{
"DisplayName": "kia",
"Name": "optima",
"Type": "2012"
}
]
}
And my table should be as the following image
I have used antd in my project and I tried to implement this functionality with antd table and could not implement as I want. I need the filter functionality too.
Can anyone suggest a solution
You need to restructure your dataSource witch children prop:
function NestedTables() {
return (
<Flexbox>
<Table
size="small"
indentSize={0}
columns={columns}
dataSource={source}
/>
</Flexbox>
);
}
When your source is:
const source = [
{
key: '1',
Code: 'SP',
children: [
{
key: '11',
Code: '5001',
DisplayName: 'audi',
Name: 'r8',
Type: '2012'
},
{
key: '12',
Code: '313',
DisplayName: 'audi',
Name: 'rs5',
Type: '2013'
}
]
},
{
key: '2',
Code: 'Code',
children: [
{
key: '21',
Code: '243',
DisplayName: 'ford',
Name: 'mustang',
Type: '2012'
},
{
key: '22',
Code: '503431',
DisplayName: 'ford',
Name: 'fusion',
Type: '2015'
}
]
},
{
key: '3',
Code: 'Message',
children: [
{
key: '31',
Code: '4311',
DisplayName: 'kia',
Name: 'optima',
Type: '2012'
}
]
}
];
And defined columns filters:
const columns = [
{
title: 'Code',
dataIndex: 'Code',
key: 'Code',
filters: [
{ text: 'SP', value: 'SP' },
{ text: 'Code', value: 'Code' },
{ text: 'Message', value: 'Message' }
],
onFilter: (value, record) => record.Code.indexOf(value) === 0
},
{
title: 'Display Name',
dataIndex: 'DisplayName',
key: 'DisplayName',
filters: [
{ text: 'audi', value: 'audi' },
{ text: 'ford', value: 'ford' },
{ text: 'kia', value: 'kia' }
],
onFilter: (value, record) =>
record.children.filter(child => child.DisplayName === value).length > 0
},
{ title: 'Name', dataIndex: 'Name', key: 'Name' },
{ title: 'Type', dataIndex: 'Type', key: 'Type' }
];
Demo:

extjs parsing nested json in template

Trying (unsuccessfully) to display data from nested json.
JSON might look something like:
{
"contacts": [
{
"id": "1",
"client_id": "135468714603",
"addresses": [
{
"id": "1",
"contact_id": "1",
"address_id": "16",
"address": {
"0": {
"id": "16",
"address": "123 Some Rd",
"address2": "",
"city": "Toen",
"state": "VS",
"zip_code": "11111",
"country": "USA"
}
}
},
{
"id": "6",
"contact_id": "1",
"address_id": "26",
"address": {
"0": {
"id": "26",
"address": "1 Other Road",
"address2": "",
"city": "Twn",
"state": "BD",
"zip_code": "11112",
"country": "USA"
}
}
}
]
},
{
"id": "10",
"client_id": null,
"addresses": [
{
"id": "8",
"contact_id": "10",
"address_id": "28",
"address": {
"0": {
"id": "28",
"address": "54 Road",
"address2": "",
"city": "TWND",
"state": "TT",
"zip_code": "11113",
"country": "USA"
}
}
},
{
"id": "9",
"contact_id": "10",
"address_id": "29",
"is_mailing_address": "0",
"is_primary_address": "0",
"display_priority": "0",
"address": {
"0": {
"id": "29",
"address": "6 Road",
"address2": "",
"city": "TOEOEOWN",
"state": "PY",
"zip_code": "11116",
"country": "USA"
}
}
},
{
"id": "10",
"contact_id": "10",
"address_id": "30",
"address": {
"0": {
"id": "30",
"address": "PO Box 9",
"address2": "",
"city": "TOYN",
"state": "GF",
"zip_code": "11118",
"country": "USA"
}
}
}
]
},
{
"id": "11",
"client_id": null,
"contact_id": "11",
"addresses": [
{
"id": "11",
"contact_id": "11",
"address_id": "33",
"is_mailing_address": "0",
"is_primary_address": "0",
"display_priority": "0",
"address": {
"0": {
"id": "33",
"address": "4 Street",
"address2": "",
"city": "TEOIN",
"state": "TG",
"zip_code": "11119",
"country": "USA"
}
}
}
]
}
]
}
I've tried mapping model fields to what I need (e.g. contacts model > addresses field > mapping: addresses), but this doesn't work because I'd need to map to addresses[0].address[0] to get the data which obviously discards the other addresses.
I've also tried playing around with associations, but this appears to be separate models and stores. The idea here is to not make a separate request for the contacts and then their addresses.
I've also tried digging into the json straight in the template (which seemed to be the most straightforward way) e.g. {addresses.address.city} which doesn't work.
The thinking is simple: grab some json, and display different parts of said json in different parts of the app.
The experience has been dreadful.
Can someone explain how to map these nested json items so that they are accessible from a template?
Template:
{
xtype: 'container',
flex: 1,
id: 'mainPanel',
items: [
{
xtype: 'dataview',
hidden: false,
id: 'clientsContacts',
minHeight: 200,
itemSelector: 'div',
itemTpl: [
'{id} | {last_name} | {first_name} | {relationship} | {addresses}'
],
store: 'Contacts'
}
]
}
Store:
Ext.define('MyApp.store.Contacts', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.Contacts'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
storeId: 'Contacts',
model: 'MyApp.model.Contacts',
proxy: {
type: 'ajax',
extraParams: {
id: '',
format: 'json'
},
url: '/api/contacts/', //the json
reader: {
type: 'json',
root: 'contacts'
}
},
listeners: {
load: {
//fn: me.onJsonstoreLoad,
//scope: me
}
}
}, cfg)]);
},
});
Model:
Ext.define('MyApp.model.Contacts', {
extend: 'Ext.data.Model',
uses: [
//'MyApp.model.Client',
//'MyApp.model.contactAddressModel'
],
fields: [
{
name: 'client_id'
},
{
name: 'id'
},
{
name: 'addresses',
mapping: 'addresses'//doesn't work
//mapping: 'addresses[0].address[0]' //works, but only for the first address duh
}
],
});
Using extjs 4.1 via Sencha Architect.
Any help would be greatly appreciated.
Thanks.
I think I got it (hopefully it's correct).
So, create a field for each nested group of data you need. So I have a Contacts model. In that model there are these fields:
id
client_id
addresses //mapped to addresses
address //mapped to addresses.address
then in the template:
<br>
<tpl for="addresses">
id: {id}<br>
addy id: {address_id}<br>
<tpl for="address">
{city} {state}, {zip}<br>
</tpl>
</tpl>
This is what the whole thing looks like:
View
Ext.define('MyApp.view.MyView', {
extend: 'Ext.view.View',
height: 250,
width: 400,
itemSelector: 'div',
store: 'MyJsonStore',
initComponent: function() {
var me = this;
Ext.applyIf(me, {
itemTpl: [
'<br>',
'<tpl for="addresses">',
' id: {id}<br>',
' addy id: {address_id}<br>',
' <b>',
' <tpl for="address">',
' {city} {state}, {zip}<br><br>',
' </tpl>',
' </b>',
'',
'</tpl>',
'',
'<hr>',
''
]
});
me.callParent(arguments);
}
});
Store
Ext.define('MyApp.store.MyJsonStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.Contacts'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'MyJsonStore',
model: 'MyApp.model.Contacts',
data: {
contacts: [
{
id: '1',
client_id: '135468714603',
addresses: [
{
id: '1',
contact_id: '1',
address_id: '16',
address: {
'0': {
id: '16',
address: '123 Some Rd',
address2: '',
city: 'Toen',
state: 'VS',
zip_code: '11111',
country: 'USA'
}
}
},
{
id: '6',
contact_id: '1',
address_id: '26',
address: {
id: '26',
address: '1 Other Road',
address2: '',
city: 'Twn',
state: 'BD',
zip_code: '11112',
country: 'USA'
}
}
]
},
{
id: '10',
client_id: null,
addresses: [
{
id: '8',
contact_id: '10',
address_id: '28',
address: {
id: '28',
address: '54 Road',
address2: '',
city: 'TWND',
state: 'TT',
zip_code: '11113',
country: 'USA'
}
},
{
id: '9',
contact_id: '10',
address_id: '29',
is_mailing_address: '0',
is_primary_address: '0',
display_priority: '0',
address: {
id: '29',
address: '6 Road',
address2: '',
city: 'TOEOEOWN',
state: 'PY',
zip_code: '11116',
country: 'USA'
}
},
{
id: '10',
contact_id: '10',
address_id: '30',
address: {
id: '30',
address: 'PO Box 9',
address2: '',
city: 'TOYN',
state: 'GF',
zip_code: '11118',
country: 'USA'
}
}
]
},
{
id: '11',
client_id: null,
contact_id: '11',
addresses: [
{
id: '11',
contact_id: '11',
address_id: '33',
is_mailing_address: '0',
is_primary_address: '0',
display_priority: '0',
address: {
id: '33',
address: '4 Street',
address2: '',
city: 'TEOIN',
state: 'TG',
zip_code: '11119',
country: 'USA'
}
}
]
}
]
},
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'contacts'
}
}
}, cfg)]);
}
});
Model
Ext.define('MyApp.model.Contacts', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id'
},
{
name: 'client_id'
},
{
name: 'addresses',
mapping: 'addresses'
},
{
name: 'address',
mapping: 'address'
}
]
});
I have verified that the above answer does work, but to note for future people, that if you don't specify the name of sub fields, you don't need the 2nd nested template. You can do it with just the first.

Resources