how can i handle my json elements - javascript

Here is my json file
{
id: '81224112234234222223422229',
type: 'message',
message: 'vacation',
attachments: [
{
type: 'template',
elements: [
{
id: '123123123123123',
title: 'job',
text: 'job',
properties: {
code: 'IO002',
value: 'messenger/IO001,messenger2(IO)/IO002,messenger3(IO)/IO003'
}
},
{
id: '123123123123123',
title: 'Date',
text: 'date',
properties: {
code: '2017-11-09~2017-11-09',
value: '2017-11-09~2017-11-09'
}
},
{
id: '123123123123123',
title: 'Sequence',
text: 'sequence',
properties: {
code: '1',
value: '1process/1,2process/1,3process/1'
}
}
]
}
],
module: 'temp'
}
i am using react.js and i want to extract all properties
result
job code: I0002
job value:messenger/IO001,messenger2(IO)/IO002,messenger3(IO)/IO003
date code:2017-11-09~2017-11-09
date value:2017-11-09~2017-11-09
sequence code:1
sequence value:1process/1,2process/1,3process/1
i tried to execute like this
const job=elements.filter(x=>x.text==='job');
const date=elements.filter(x=>x.text==='date');
const sequence=elements.filter(x=>x.text==='sequence');
is it proper way to use filter or another way to extract data from json file?
i am new to react.js and es6,javascript.so i have no idea to display each property.
how can i solve my problem? pz give me a tip.i want to extract properties

You can use
var yourobject=JSON.parse(jsondata);
const job=yourobject.job;

Related

Dynamically add values to specific property in object - Fluent UI React ContextualMenu

I have the following ContextualMenu structure inside my SPFx Extension build with Fluent UI React:
const menuProps: IContextualMenuProps = {
items: [
{
key: 'Access',
itemType: ContextualMenuItemType.Section,
sectionProps: {
topDivider: true,
bottomDivider: true,
title: 'Sites you have access to',
items: [
{ key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
{ key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
],
},
},
],
};
I also a MS Graph call running getting me some SharePoint Sites & Teams.
I would now like to push those dynamic responses to the to the menuProps at the right place.
So basically add the dynamic array into the nested items object.
items: [
{ key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
{ key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
],
How can I target that "object"? (hope I understand correctly and items is an object...)
Is there a way to do this using array.push()?
To make this library agnostic, it would look something like this:
const obj = {
items: [
{
key: 'Access',
itemType: '',
sectionProps: {
topDivider: true,
bottomDivider: true,
title: 'Sites you have access to',
items: [
{ key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
{ key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
],
},
},
],
};
obj.items[0].sectionProps.items.push({ key: 'DynamicValue3.1', text: 'DynamicValue3.2' })
console.log(obj.items[0].sectionProps.items)
Your console.log would return this:
[
{ key: 'DynamicValue1.1', text: 'DynamicValue1.2' },
{ key: 'DynamicValue2.1', text: 'DynamicValue2.2' },
{ key: 'DynamicValue3.1', text: 'DynamicValue3.2' }
]
If you can access menuProps: IContextualMenuProps, then just replace obj with the necessary variable.

How to transform only 2 properties but keep remaining same as is in a nested object structure?

Apologies if title is not clear.
I am using json2csv npm package to prepare csv from json object and this package allows us to add a hook to transform object before actual csv line is prepared.
I only need to manipulate two properties out of all. How can I do this effectively? My code feels too bloated.
const {
Parser: Json2csvParser,
transforms: { unwind },
} = require('json2csv');
const json2csvFields = [
{ value: 'root.filename', label: 'File Name' },
{ value: 'issue.root.priority', label: 'Priority' },
{ value: 'issue.root.url', label: 'URL' },
{ value: 'issue.root.startline', label: 'Start Line' },
{ value: 'issue.root.stopline', label: 'Stop Line' },
{ value: 'issue.root.startcolumn', label: 'Start Column' },
{ value: 'issue.root.stopcolumn', label: 'Stop Column' },
{ value: 'issue.root.issuename', label: 'Issue Name' },
{ value: 'issue.root.issuecategory', label: 'Issue Category' },
{ value: 'issue._', label: 'Issue Description' },
];
const sampleData = [
{
root: {
filename:
'/home/users/john-doe/workspace/foo-project/src/main/classes/foo.cls',
},
issue: {
root: {
priority: 1,
url: 'www.example.com',
startline: 100,
stopline: 105,
startcolumn: 20,
stopcolumn: 25,
issuename: 'blah',
issuecategory: 'Category A',
},
_: ' Fox ',
},
},
];
const json2csvOptions = {
fields: json2csvFields,
quote: '',
header: true,
transforms: [
(item) => ({
'root.filename': item.root.filename.replace(
'/home/users/john-doe/workspace/foo-project/src/main/classes/',
''
),
'issue._': `"${item.issue._.trim()}"`,
// Except for the above two, everything else doens't need any transformation.
'issue.root.priority': item.issue.root.priority,
'issue.root.url': item.issue.root.url,
'issue.root.startline': item.issue.root.startline,
'issue.root.stopline': item.issue.root.stopline,
'issue.root.startcolumn': item.issue.root.startcolumn,
'issue.root.stopcolumn': item.issue.root.stopcolumn,
'issue.root.issuename': item.issue.root.issuename,
'issue.root.issuecategory': item.issue.root.issuecategory,
}),
],
};
const json2csvParser = new Json2csvParser(json2csvOptions);
const csv = json2csvParser.parse(sampleData);
console.log(csv);
This prints below output:
File Name,Priority,URL,Start Line,Stop Line,Start Column,Stop Column,Issue Name,Issue Category,Issue Description
foo.cls,1,www.example.com,100,105,20,25,blah,Category A,"Fox"
EDIT: Updated code to a working example.
After listing the two properties with special treatment, use Object.fromEntries and Object.entries to transform all the issue.root properties to their flat structure with .s in the property names. Then that object can be spread into the returned object.
const transformsFn = ({ root, issue }) => ({
'root.filename': root.filename.replace(
'/home/users/john-doe/workspace/foo-project/src/main/classes/',
''
),
'issue._': `"${issue._.trim()}"`,
...Object.fromEntries(
Object.entries(issue.root).map(
([key, val]) => [`issue.root.${key}`, val]
)
),
});
const json2csvOptions = {
fields: json2csvFields,
quote: '',
header: true,
transforms: [transformsFn],
};

Generate valid v-model value using dot notation string as object reference to the data

Basically i've made proyxy-component which renders different components based on what the :type is and it works great. The point is that I create a schema of the form controls and a separate data object where the data from the form controls is stored. Everything is working good but i have a problem when formData object contains nested objects.
In my example test.test1
How can i make the v-model value dynamic which is generated based on what the string is.
My Compoennt
<proxy-component
v-for="(scheme, index) in personSchema.list"
:key="index"
:type="scheme.type"
:props="scheme.props"
v-model="formData[personSchema.prefix][scheme.model]"
v-validate="'required'"
data-vv-value-path="innerValue"
:data-vv-name="scheme.model"
:error-txt="errors.first(scheme.model)"
></proxy-component>
Data
data() {
return {
selectOptions,
formData: {
person: {
given_names: '',
surname: '',
sex: '',
title: '',
date_of_birth: '',
place_of_birth: '',
nationality: '',
country_of_residence: '',
acting_as: '',
test: {
test1: 'test',
},
},
},
personSchema: {
prefix: 'person',
list: [
{
model: 'given_names',
type: 'custom-input-component',
props: {
title: 'Name',
},
},
{
model: 'surname',
type: 'custom-input-componentt',
props: {
title: 'Surname',
},
},
{
model: 'test.test1',
type: 'custom-input-component',
props: {
title: 'test 1',
},
},
{
model: 'sex',
type: 'custom-select-component',
props: {
title: 'Sex',
options: selectOptions.SEX_TYPES,
trackBy: 'value',
label: 'name',
},
},
],
},
};
},
I would recomment you to write a vue-method (under the data section) that returns the object for v-model
v-model="resolveObject(formData[personSchema.prefix][scheme.model])"
or
v-model="resolveObject([personSchema.prefix] , [scheme.model])"
There you can do handle the dot-notation and return the proper nested property.
I don't think it's possible directly with v-model, you can take a look at:
https://v2.vuejs.org/v2/guide/reactivity.html
Maybe the best solution would be use a watch (deep: true) as a workaround.
(I would try first to use watch properties inside formData[personSchema.prefix][scheme.model].)

Typeahead js with dynamic multiple datasets

In typeahead js while using multiple data-sets (as seen here typeahed multiple datasets) each category is sent as a separate parameter while initialising the typeahead. Is it possible to have dynamic categories from a single data source instead of multiple data sources.
$('#multiple-datasets .typeahead').typeahead({
highlight: true
},
{
name: 'nba-teams',
display: 'team',
source: nbaTeams,
templates: {
header: '<h3 class="league-name">NBA Teams</h3>'
}
},
{
name: 'nhl-teams',
display: 'team',
source: nhlTeams,
templates: {
header: '<h3 class="league-name">NHL Teams</h3>'
}
});
Here nba-teams and nhl-teams are sent as separate parameters to typeahead().IS there a way to send N datasets or specify the category the data belongs to like
data = [
{ value: 'Chicago Blackhawks', data: { category: 'NHL' } },
{ value: 'Chicago Bulls', data: { category: 'NBA' } },
{ value: 'LA Galaxy', data: { category: 'MLS' } },
{ value: 'Seattle Founders', data: { category: 'MLS' } },
]
try using signature: typeahead(options, [*datasets]); it worked for me with the latest version combiined with Bloodhound object for source property.
* ref-usage(internal project)

Load JSON in Ext store, associations missing

I'm using Ext 4.1. I have some issues with loading json data with associations. The flat data gets loaded perfectly, only the 'hasMany' doesn't work. (if loaded there nowhere to be found). If a record is loaded I want to be able to get the 2 stores of Attendee's and the 1 store of documents.
I can also change the JSON format to a better format (if you have suggestions let me know!)
I have this json data.
This is my first model:
Ext.define('App.model.package.LabVisit', {
extend: 'Ext.data.Model',
requires: [
'App.model.package.Attendee',
'App.model.package.Document'
],
idProperty: 'labVisitID',
fields: [
{
mapping: 'lab_visit_id',
name: 'labVisitID',
type: 'int'
},
{
mapping: 'lab_id',
name: 'labID',
type: 'int'
},
... some more irrelevant...
{
mapping: 'comments',
name: 'comments'
},
{
name: 'upddate'
}
],
hasMany: [
/* edit: added foreignKey (also tried with: lab_visit_id) */
{ model: 'package.Attendee', name: 'attendeeLabList', associationKey:'attendee_lab', foreignKey: 'labVisitId' },
{ model: 'package.Attendee', name: 'attendeeEmpList', associationKey:'attendee_emp', foreignKey: 'labVisitId' }
{ model: 'package.Document', name: 'document', associationKey:'document' },
]
});
I have following attendee model:
Ext.define('App.model.package.Attendee', {
extend: 'Ext.data.Model',
fields: [
/* edit: added this field */
{
mapping: 'lab_visit_id',
name: 'labVisitId'
},
{
mapping: 'attendee_id',
name: 'AttendeeID'
},
{
mapping: 'first_name',
name: 'firstName'
},
{
mapping: 'last_name',
name: 'lastName'
},
{
name: 'email'
}
]
});
following document model:
Ext.define('App.model.package.Document', {
extend: 'Ext.data.Model',
fields: [
{
mapping: 'document_id',
name: 'docID'
},
{
mapping: 'document_name',
name: 'docName'
},
{
mapping: 'document_mimetype',
name: 'mimeType'
},
{
name: 'uploadID'
}
]
});
Finally my store:
Ext.define('App.store.package.LabVisit', {
extend: 'Ext.data.JsonStore',
requires: [
'App.model.package.LabVisit'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.merge({
storeId: 'labVisitStore',
model: 'App.model.package.LabVisit',
remoteSort: true,
proxy: {
type: 'ajax',
api: {
read: API_URLS.getVisitList //url to the json
},
reader: {
type: 'json',
root: 'rows'
}
}
}, cfg)]);
}
});
Edit:
I've added the foreign key in the model and added it to the hasMany
Still no difference. This is my output:
I also find it a strange: If it's broken I expect an exception. And there are 2 mysterious stores always present but I don't have a clue why or what's the purpose.
The problem was in this part:
hasMany: [
{ model: 'package.Attendee', name: 'attendeeLabList', associationKey:'attendee_lab' },
{ model: 'package.Attendee', name: 'attendeeEmpList', associationKey:'attendee_emp' },
{ model: 'package.Document', name: 'document', associationKey:'document' },
]
#Izhaki helped me a lot. Thanx! Especially with the fiddle. I started there and begun with switching the code with my code piece by piece. Until I saw the model was the problem.
models should be defined like this: App.model.package.Attendee
I think it's sad that the framework doesn't show a significant error/warning if a model isn't recognised/doesn't excist/isn't supplied... But meh, it works now.

Categories