How to generate dynamically two arrays at same time with Formik - javascript

I working in a form who generate fields dynamically using formik with the <FieldArray />that acts as a functional component.
So, I have this object to send on submit to my backend:
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "",
"propsTwo": "",
"view": 0,
}
]
}
],
"typeOptions": []
}
As you can see, I have two arrays to working in this json object, one is Tapes who has Elements to work together and typeOptions who has values to send. My proposal is to send in a form with dynamic fields to my backend when whenever the user add new tapes and add new field props which will be rendered later in a mobile app.
Assuming the user added two new tapes and added two new elements for each one, the result of this json would be this:
{
"tapes": [
{
"name": "TapeOne",
"elements": [
{
"propsOne": one,
"propsTwo": two,
"view": 0,
},
{
"propsOne": 1,
"propsTwo": 2,
"view": 0,
}
]
},
{
"name": "TapeTwo",
"elements": [
{
"propsOne": one,
"propsTwo": two,
"view": 0,
},
{
"propsOne": 1,
"propsTwo": 2,
"view": 0,
}
]
}
],
"typeOptions": []
}
Well, so far so good, I can form a dynamic generation of Tapes and Elements according to the user's request, but there is a moment when the user asks for an option selector and the value I get in Elements is in the View, where number by the value of 1 is required.
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "",
"propsTwo": "",
"view": 1,
}
]
}
],
"typeOptions": [
{
"values": []
}
]
}
It is at this point that I need to retrieve the values that it passes on in these fields that will be dynamically generated and insert them into a new array that is called typeOptions in its values, the flow being like this:
The user will ask for a field who has multiple fields, like a selector.
This field will be generated in Tapes, Elements with the value being assigned to view with 1
The user will pass the values in these fields and they will be placed in typeOptions.values
So, the user add this new field and when this happens, I need pass the values that will be passed on fields will be generated for him.
The result needs be like this:
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "One",
"propsTwo": "Two",
"view": 1,
}
]
}
],
"typeOptions": [
{
"values": ["ValueOne", "ValueTwo", "ValueThree"]
}
]
}
Or when two Elements has the same view like 1:
{
"tapes": [
{
"name": "",
"elements": [
{
"propsOne": "One",
"propsTwo": "Two",
"view": 1,
},
{
"propsOne": "1",
"propsTwo": "2",
"view": 1,
}
]
}
],
"typeOptions": [
{
"values": ["ValueOne", "ValueTwo", "ValueThree"]
},
{
"values": ["Value1", "Value2", "Value3"]
}
]
}
I've already tried to use two <FieldArray /> having one inside the other, as I already do for Tapes and Elements, because with this I could use the map function to get the view value and add a conditional to permeate two new <FieldArray /> to add the values not only for each object selected inside the typeOptions, but also for each value that is inserted together.
What is the best way and best practice to do this?

Related

How can we access the Child Key from Object

I'm trying to loop my child array but it's not working. It's working fine which it's first items but not working on the child elements.
"candidateApplication": [
{
"label": "Are you currently attending school?",
"id": "ap_currentschool",
"value": "",
"required": "N",
"type": "radio",
"display": null,
"list": [
{
"searchCode": "yes",
"searchValue": "yes"
},
{
"searchCode": "no",
"searchValue": "no"
}
],
"onSelect": [
{
"yes": [
{
"label": "Estimated Completion Date",
"id": "ap_compdate",
"value": "",
"required": "N",
"type": "date",
"display": null,
"list": null,
"onSelect": null
}
],
"no": null
}
]
},
]
I am easily access my data to looping lists like obj.candidateApplication.list But I am not able to loop through obj.candidateApplication.onSelect.yes.
Can anybody please guide me how can I fix that issue.
enter image description here
You are accessing obj.candidateApplication.onSelect.yes which is undefined because obj.candidateApplication.onSelect is an array of objects.
You probably want to loop over obj.candidateApplication.onSelect and then for each object you can access the yes property as you wish:
$.each(onSelect, function (index, element) {
$.each(element.yes, function (x, y) {
// your code here
})
});
Edit: As pointed by Heritic Monkey in the comments, obj.candidateApplication is an array as well, but in the picture attached to the question, there's already a local variable called onSelect, loop through that instead of obj.candidateApplication.onSelect because it's undefined. (at least it should be, we don't know what your code is doing)

How to navigate to the last child of a hierarchical data stored in SQL database based on the JSON passed in the request body in nodeJS?

I have a need to get the last child of a hierarchy based on the JSON data passed from the request body.
The request body looks like this:
{
"hierarchy": [
{
"id": 1,
"name": "A",
"level": 0,
"labels": [
"grandparent",
"parent",
"child"
],
"categories": [
{
"id": 2,
"name": "B",
"level": 1,
"action": "kill",
"categories": [
{
"id": 3,
"name": "C",
"level": 2,
"action": "kill",
"categories": []
}
]
}
],
"action": "kill"
}
]
}
The data will be stored in the SQL database like this:
Based on the data sent from the req body, I need to navigate to the last child in the database , in this case: C and then delete them.
Currently Im using this:
const killfamily = async (id, transaction, header = {}) => {
//need recursive method here
await family.destroy({ where: { parent_id: id }, transaction: transaction });
const result = await family.destroy({ where: { fid: id }, transaction: transaction });
return result;
Current approach is not working as im trying to delete the parent first. I want to achieve this using recursive method i.e Go to the inner most/ last child and perform destroy on it.
Any help is appreciated. Thank you

Updating MongoDB nested array using same path as the search query

I have the following problem, I want to update a document with a path id.metadata.panels.items where panels is an array and items is an array. My search query looks at the items and displays only those that match the criteria of metadata.panels.items.member.type: 'owner' - then I want to update the 'owner to 'account'.
When I am trying to update having the search path same as update path I get an error message saying: cannot use the part metadata.panels.items.member.type to traverse the element.
The documents have their own
How can I resolve this problem?
I have already tried to go through the collection using nested forEach statements to iterate through each of the arrays but I am not sure what to do next.
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
var newFields = [];
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
})
})
})
Sample document structure:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Owner]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
Expected result:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Account]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
I figured it out.
var newFields = [];
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
// I have generated update statements as strings
// first list is always position 0 and this goes to the statement
// second list get's populated from itemIndex
// added them to the newFields list
})
})
})
newFields.forEach(function(i){
eval(i)
})

Creating a valid server response from javascript/Angular

My JSON
{
"RECORDS": [
{
"Id": 23040035705987,
"arriveddate": "2015/04/24",
"expirationDate": null,
"replacedDate": null,
"processDate": "2015/04/24"
},
{
"Id": 23070041800654,
"arriveddate": "2015/04/24",
"expirationDate": null,
"replacedDate": null,
"processDate": "2015/04/27"
},
{
"Id": 23040035705984,
"arriveddate": "2015/04/24",
"expirationDate": null,
"replacedDate": null,
"processDate": "2015/04/24"
},
{
"Id": 23040035705983,
"arriveddate": "2015/04/24",
"expirationDate": null,
"replacedDate": null,
"processDate": "2015/04/24"
}
],
}
Expected Object
{
"processDate": [
"2015/04/24",
"2015/04/27"
],
"Id": [
[
23040035705983,
23040035705984,
23040035705987
],
[
23070041800654
]
]
}
i need to do a mapping based on the process date like in my expected object i have two dates which are the unique dates of all my JSON and in the next ids i have each id which belongs to that corresponding process dates right now i have been able to get the unique process dates but in the next ids i am not able to do can you please provide an example as to how i should loop through to achieve the same in angular
You could use two nested forEach loops.
angular.forEach(obj.processDate, function(processValue, processIndex,date) {
angular.forEach(obj2.RECORDS, function (recordValue, recordIndex,records) {
if (processValue === recordValue["processDate"]) {
if (!obj["Id"][processIndex]) {
obj["Id"][processIndex]=[];
}
obj["Id"][processIndex].push(recordValue["Id"]);
});
});
}

Handsontable Replace autocomplete values with key before posting

I am using HandsOnTable to make editing database tables more interactive on my site.
HandsOnTable fulfils nearly all my requirements except that some columns in my database actually store foreign keys rather than local string values.
In the UI I would like these columns to appear as dropdown menus where the user selects a readable value mapped to the previously mentioned foreign key (I.e. something like an HTML name/value select).
Unfortunately HandsOnTable does not have such a cell type. The closest thing to it is autocomplete. This allows me to create a dropdown, but it only contains values; no corresponding keys. Here is how it is created:
"source": ["Jebediah", "Bob", "Bill", "Buzz"]
So what I am planning is to send two Json strings from the server:
One containing the parameters needed by HandsOnTable to render the table:
{
"data": [
{ "ID": 1, "Description": "Crude", "Volume": 204, "Customer": "jebediah" },
{ "ID": 2, "Description": "Hidrogen", "Volume": 513, "Customer": "Bob" },
{ "ID": 3, "Description": "Coal", "Volume": '67', "Customer": "Bill" },
{ "ID": 4, "Description": "Wood", "Volume": '513', "Customer": "Buzz" }
],
"columns": [
{ "data": "ID", "type": "numeric" },
{ "data": "Description", "type": "text"},
{ "data: "Volume", "type": "numeric" },
{ "data": "color", "type": "autocomplete", "strict": "true",
"source": ["Jebediah", "Bob", "Bill", "Buzz"]}
]
}
The second mapping keys to values
{
"mappings": [
{"key": 0, "value": "Jebediah"},
{"key": 0, "value": "Bob"},
{"key": 0, "value": "Bill"},
{"key": 0, "value": "Buzz"}
]
}
So far so good. Now for the tricky part:
HandsOnTable has a function (getData()) that allows me to retrieve the tables data as a Json string ready to be sent back to the server:
var jdata = myHandsOnTable.getData();
Where jdata would look something like this:
"data": [
{ "ID": 1, "Description": "Crude", "Volume": 204, "Customer": "jebediah" },
{ "ID": 2, "Description": "Hidrogen", "Volume": 513, "Customer": "Bob" },
{ "ID": 3, "Description": "Coal", "Volume": '67', "Customer": "Bill" },
{ "ID": 4, "Description": "Wood", "Volume": '513', "Customer": "Buzz" }
]
Now before posting, I would like to replace that values for the Customer node with their matching pair key within the mappings json string.
How can I best achieve this in JavaScript/JQuery?
Is there a function that works something as follows?:
jdata.replaceNode('node', mappings)
Thanks
I had a similar issue and here's what I did...
For each foreign key column, I stored 2 values in handsontable; one for the id itself, which I set as a hidden column and the other is the user friendly readable text value as dropdowns.
Everytime the value of a dropdown is changed, I also change the corresponding hidden id. In my case I have a dropdown outside the handsontable as a filter which I use to map key/value pairs, but you could use Hashtables or anything else.
Now the code...
Handsontable config:
afterChange: function (changes, source) { AfterChange(changes, source); }
After change event (called everytime there is a change in the table):
function AfterChange(Changes, Source) {
if (Source === 'loadData') {
return; //don't save this change
}
var rowIndex = 0, columnID = 1, oldTextVal = 2, newTextVal = 3, ntv = '', nv = '';
$(Changes).each(function () {
if (this[columnID] === 'CategoryID') {
// Do nothing...
//To make sure nothing else happens when this column is set through below
}
else if (this[columnID] === 'CategoryName') {
ntv = this[newTextVal];
//This is where I do my mapping using a dropdown.
nv = $('#CategoriesFilterDropdown option').filter(function () { return $(this).text() === ntv; }).val();
//13 is my CategoryID column
$container.handsontable('setDataAtCell', this[rowIndex], 13, nv);
}
});
}
}
This way, you change the foreign keys as you and don't need to loop through it all before saving. It also makes it easy to send the table data as is back to server.
In summary,
The user interacts with CategoryName column (which is of type autocomplete).
The CatgoryID column is hidden to the user by setting the column width to 0 using the colWidths option of handsontable.
When the CategoryName field changes, use afterChange event to set the corresponding CategoryID column. In my case, I use a dropdown somewhere else on the page to map Name => ID, but you can use other means such as a hashtable.
I hope it makes sense...

Categories