Dartlang: How to get key and values from json? - json

I'm having a little problem and couldn't figure it out. I created a table with checkbox and it's working and can save to json without a problem. Now i wanna make my checkboxes have their default values set from json data when the page loads (to make it easier to edit). Anyway here is my code:
//row index
var index = 0;
//gets full info of student
var responseStudent = rpc.call('db.findOne', ['StudentAnket', {
'_id': '${this.objId}'
}]);
result = responseStudent['result'];
//gets info needed for my table
//{anket: true, request: true, statement: false, etc...}
var resultMat = result['listmaterial'];
//materials is a list which contains id, name of rows
materials.forEach((m) {
//creating table body
index = index + 1;
tbody.append(new Element.tr()
..append(new TableCellElement()..text = index.toString())
..append(new TableCellElement()..append(new LabelElement()
..text = m['name']
..setAttribute('for', m['id'])))
..append(new TableCellElement()..append(new InputElement()
..id = m['id']
..type = "checkbox"
..checked = "VALUE TAKEN FROM JSON")));
});
So how can i get keys and values from resultMat and set checked property for each checkbox?
Edit:
List materials = [{
'id': 'anket',
'name': 'Student anket'
}, {
'id': 'request',
'name': 'Request'
}, {
'id': 'statement',
'name': 'Statement'
}, {
'id': 'marklist',
'name': 'Mark List'
}];

Your information how your materials structure looks like is not clear. A List has only one value not two ('id, 'name of rows'). First you have to ensure that your JSON is not a String but a Dart data structure (Lists, Maps, values).
You can take a look at the answers to this questions to learn how this works
Dart Parse JSON into Table
Then you should be able to access the value like
..checked = resultMat[m['id']] ;

Related

How to store n number of inputs into an array using mysql in express.js

Hi I a beginner to the web development
I wanted to accept n number of the instance(n is inputted by the user) from the user and then store those values in an array-like structure so that my frontend can have access to it. Can this be done using mysql ?. I was reading StackOverflow posts that mentioned that it is not a good idea to use MySQL for this. However I am already kind of deep into my project so I want to clarify this.
Is this feasible using MySQL?
I guess you want to store something like object or array of something
let's say that in your front end there is a form with input and button
where the input is Add More Columns and the input is value so in your backend you will get an array of objects like
[
{ question: '1', answer: 'Answer1' },
{ question: '2', answer: 'Answer2' },
{ question: '3', answer: 'Answer3' },
{ question: '4', answer: 'Answer4' }
]
you can make a table
id | userId | payload
where id is generated by SQL
userId that you injected in the token (or something else to relate the user with his payloads)
and payload that contains the information that you need to store
const saveUserPayLoads = async (req, res) => {
const { payloads } = req.body;
const { id } = req.user
const data = []
for(payload of payloads) data.push(DBModule.create({ payload: JSON.stringify(payload), userId: id }))
return res.status(201).json({
message: 'Done',
success: true,
data
})
}

Remove duplicate object copies from array of objects

I have an array of objects that I get from an API. The property names are dynamic (meaning I don't have an extensive list of all of them). How can I get an array of all distinct objects? The contract specifies that if key is equal value is also equal. I tried to look around but I found nothing quite like this problem.
[ 20:31:28
{
'product-management': 'Product management'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
}
]
Spread the array into Object.assign() to merge all objects to a single one. Since all objects properties are unique, this will leave only one key (and value) from the duplicates. Then convert to [key, value] pairs with Object.entries(), and map back to individual objects:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([k, v]) => ({ [k]: v }))
console.log(result)
Going with #Bergi's suggestion, you can also convert this to a saner API while removing duplicates:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([key, value]) => ({ key, value }))
console.log(result)

Accessing Data in JSON [Nodejs]

I have some JSON that when converted to an Object it looks like the following:
{
'SOME RANDOM STRING':
{
'Article Headline': 'headline',
'Article Image URL': 'image url',
'Article Published Date': 'date',
'Article URL': 'article url',
'Category': 'mental illness,',
'Location': 'place',
'Source Name': 'source'
}
}
I have it stored in an array called results. How would I be able to access the values within Location as result.location doesn't work.
If its a JSON, you don't have to convert it into an array. You can parse it directly something like below.
var obj = {
'-KzZaDXhWRwdzfKUf5tl':
{ 'Article Headline': 'headline',
'Article Image URL': 'image url',
'Article Published Date': 'date',
'Article URL': 'article url',
'Category': 'mental illness,',
'Location': 'place',
'Source Name': 'source' }
}
console.log(obj['-KzZaDXhWRwdzfKUf5tl'].Location);
The above prints place to the screen.
The path to the Object would be results[0]['RANDOM STRING'].location, however since you don't know the RANDOM STRING then it'd be best to use non referential methods to access the nested object.
Thankfully there are many tools in recent version of NodeJS/Javascript to do just this!
Array.prototype.map(function(item, index, array), context) seems like the function you want! It will create a new array based on the return of the function as applied to each thing in the array.
Then you can change each object by using other tools built onto the object itself like
// array of keys, useful for looking for a specific key
Object.keys(someReallyObtuseObject)
// array of VALUES! Awesome for looking for a specific data type
Object.values(someReallyObtuseObject)
Checking Node Green for Object.values shows it's available in NodeJS 7.10 or greater and for Object.keys shows it is available as far back as 4.8.6!
Don't forget though that these transform the object to an array. After that you can use forEach, filter, map, and many other array methods to access the data!
An Example
Say I have an array from a database called results
const results = [{...},{...},...];
I want to find a result with the identifier I know
// I will either find the result, or receive undefined
let result = results.filter(r => r[key] == identifier)[0];
However in my result the object has a key called "related posts" and it is an object with a key being a unique ID for each related post. I want to access said posts, but I don't know their unique IDs, so I want to convert it to an array to make processing it easier
// This gives me an array of related posts with their ID now nested inside them
let relatedPosts = Object.keys(result['related posts']).map(k => {
let r = result['related posts'][k];
r.id = k;
return r;
});
Now I can go over my related posts easily, and I never had to know the ID of the post. Let's say I want to console.log each post(you would really never want to do this)
relatedPosts.forEach(console.log);
Easy!
Example 2, getting the location from an array of users
Users are defined as an object with keys 'first', 'last', 'location'
const users = [{...},{...},...]
let locations = users.map(user => user.location)

Sending grouped json data with ajax

I'm using extJS version 4.0 to generate a entry form. On that form there is a save button that sends all the fielddata to php via ajax. As transfer protocol for the data itself I'm using json.
As I need to make a dynamical (general) routine for processing this data (as that one form won't be the only form in that project) I would need that json data grouped somehow. One of the requirements I have is that I need the "fieldnames" to be as they are (as I use the fieldnames I get transmitted to me to access the approopriate coloumns in the database in the automatic save routine).
My question here is is there any way to somehow group the data that is transmitted via json (thus that extJS groups it).
As a simplified example:
On the entryform I'm saving data for 2 tables (1. Person 2. bankaccount) which have the following fields shown on the form:
-firstname
-lastname
for person
and
-account number
-bank number
for bankaccount
(the stores are accordingly)
Is there a way with extJS to group this data acordingly, thus generate something like this?
{"person":[{"firstname": "Mark", "lastname":"Smith"}],"bankaccount":[{"account number":123112,"bank number":1A22A1}]}
Currently I'm getting something like this:
{"firstname": "Mark", "lastname":"Smith","account number":123112,"bank number":1A22A1}
Both person and bankaccount are in their separate stores.
Tnx.
Well, you've two stores: one for 'person' and one for 'bankaccount'.
Ext.define ('Person', {
extend: 'Ext.data.Model' ,
fields: ['firstname', 'lastname']
});
Ext.define ('BankAccount', {
extend: 'Ext.data.Model' ,
fields: ['accountnumber', 'banknumber']
});
var personStore = Ext.create ('Ext.data.Store', {
model: 'Person' ,
data: [
{firstname: 'foo', lastname: 'bar'} ,
{firstname: 'zoo', lastname: 'zar'} ,
{firstname: 'too', lastname: 'tar'} ,
{firstname: 'goo', lastname: 'gar'} ,
{firstname: 'moo', lastname: 'mar'}
]
});
var bankAccountStore = Ext.create ('Ext.data.Store', {
model: 'BankAccount' ,
data: [
{accountnumber: 10000, banknumber: 10000} ,
{accountnumber: 20000, banknumber: 20000} ,
{accountnumber: 30000, banknumber: 30000} ,
{accountnumber: 40000, banknumber: 40000} ,
{accountnumber: 50000, banknumber: 50000}
]
});
Then, you want to dump these stores as JSON. No problem!
Make a container (jsonData) and then fill it up with your stores:
var jsonData = {
person: [] ,
bankaccount: []
};
personStore.each (function (person) {
jsonData.person.push (person.data);
});
bankAccountStore.each (function (bank) {
jsonData.bankaccount.push (bank.data);
});
console.log (Ext.JSON.encode (jsonData));
And this is the output on the console:
{"person":[{"firstname":"foo","lastname":"bar"},{"firstname":"zoo","lastname":"zar"},{"firstname":"too","lastname":"tar"},{"firstname":"goo","lastname":"gar"},{"firstname":"moo","lastname":"mar"}],"bankaccount":[{"accountnumber":10000,"banknumber":10000},{"accountnumber":20000,"banknumber":20000},{"accountnumber":30000,"banknumber":30000},{"accountnumber":40000,"banknumber":40000},{"accountnumber":50000,"banknumber":50000}]}
Is that what you've requested?
Here's the fiddle

Sencha Touch 2 read values from key AND value from nested JSON

I am trying to load some JSON, in which I store a lot of variables about some 100 anaesthetic drugs for pediatric patients.
The actual values get calculated before from patient's weight, age etc.:
Example:
var propofolInductionTitle = propofolName + ' ' + propofol0PercentConcentration + '- Induktion';
var propofol0InductionDosageMG = (Math.round(kg * 2 * 10) / 10) + ' - ' + (Math.round(kg * 5 * 10) / 10);
I then create my drug as a block of json consisting of the variables I need which are later to be replaced by the calculated values. I specifically try to avoid Strings in the JSON to allow for easier localization to english and french when all variables are defined in the math block.
var hypnotikaJSON = {
"thiopentalTitle": [
{"thiopentalBrandName": ""},
{"vialContentTitle": "thiopentalVialContent"},
{"solutionTitle": "thiopentalSolution"},
{"concentrationTitle": "thiopentalConcentration"},
{"dosageString": "thiopentalDosageString"},
{"atWeight": "thiopentalDosageMG"},
{"thiopentalAtConcentration": "thiopentalDosageML"}
],
"propofolInductionTitle": [
{"propofolInductionBrandName": ""},
{"propofolVialContentTitle": "propofolInductionVialContent"},
{"propofolSolutionTitle": "propofolSolution"},
{"propofolConcentrationTitle": "propofolInductionConcentration"},
{"propofolInductionDosageStringTitle": "propofolInductionDosageString"},
{"atWeight": "propofolInductionDosageMG"},
{"propofolAtInductionConcentration": "propofolInductionDosageML"}
],
"propofolSedationTitle": [
{"propofolSedationBrandName":""},
{"propofolVialContentTitle":"propofolSedationVialContent"},
{"propofolSolutionTitle":"propofolSolution"},
{"propofolConcentrationTitle":"propofolSedationConcentration"},
{"propofolSedationDosageStringTitle":"propofolSedationDosageString"},
{"atWeight":"propofolSedationDosageMG"},
{"propofolAtSedationConcentration":"propofolSedationDosageML"}
],
"laryngealMaskTitle": [
{"laryngealMaskSizeTitle":"laryngealMaskSize"},
{"laryngealMaskCuffSizeTitle":"laryngealMaskCuffSize"},
{"laryngealMaskBiggestETTTitle":"laryngealMaskBiggestETT"},
{"laryngealMaskBronchoscopeSizeTitle":"laryngealMaskBronchoscopeSize"}
]
};
My specific need is that the JSON reader has to give me the key AND value of each object as I need both to populate a template. The reason ist that the fields for the drugs are different in parts. Some have additional routes of administration so I have another key:value pair a different drug doesnt have. Some are given both as bolus and per drip, some arent. So no convenient json structure ist possible.
I found an answer by rdougan here that partly allowed me to do just that:
Model:
Ext.define('my.model.Drug', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'value']
}
});
Custom Json Reader:
Ext.define('Ext.data.reader.Custom', {
extend: 'Ext.data.reader.Json',
alias: 'reader.custom',
getRoot: function (data) {
if (this.rootAccessor) {
data = this.rootAccessor.call(this, data);
}
var values = [],
name;
for (name in data) {
values.push({
name: name,
value: data[name]
});
}
return values;
}
});
Store:
var store = Ext.create('Ext.data.Store', {
fields: ['name', 'value'],
data: hypnotikaJSON,
autoLoad: true,
proxy: {
type: 'memory',
reader: {
type: 'custom'
}
}
});
Panel:
this.viewport = new Ext.Panel({
fullscreen: true,
layout: 'fit',
items: [{
xtype: 'list',
itemTpl: '<p class="description">{name}</p><p class ="values">{value}</p>',
store: store
}]
});
Unfortunately I'm a physician and no programmer, and after a lot of reading I cant find out to apply this to a nested JSON. The custom reader seems to only go for the first level.
I could do it without a reader, without a store with just a lot of plan html around each entry, that has proven to be very very slow though so I would like to avoid it while updating from Sencha Touch 1.1. and better do it right this time.
Could you please point me to a way to parse this ugly data structure?
Thank you
I don't know much about extending JSON readers, so just guessing, but maybe you are supposed override the 'read' method? Then you can go over the JSON as you wish
Also, if you have control over the JSON you should consider changing it.
Usually, the keys in JSON should be the same throughout all items in the array.
keys are not data, they are metadata.
So, if you do have different properties between different drugs, then something like this might be a solution:
[{
name: 'Propofol 1%',
properties: [
{title: 'induction', value: '22-56g'},
{title: 'Sedation', value: '22'},
etc.
]},
{name: 'nextDrug'}
etc..