I would like to know if there is a better way to deal with nested forEach when it comes to dealing with objects with properties that are nested arrays themselves.
My object (summarized):
{
...,
"tx_responses": [
{
...
"logs" : [
{
...,
"events": [
{
"type": "coin_received",
"attributes": [
{
"key": "receiver",
"value": "somesome"
},
{
"key": "amount",
"value": "somesome"
}
]
},
...
{
"type": "transfer",
"attributes": [
{
"key": "recipient",
"value": "somesome"
},
{
"key": "sender",
"value": "somesome"
},
{
"key": "amount",
"value": "somesome"
}
]
},
{
"type": "withdraw_rewards",
"attributes": [
{
"key": "amount",
"value": "somesomesomehere"
},
{
"key": "validator",
"value": "somesome"
}
]
},
...
]
}
],
...
I am essentially trying to extract all { key: 'amount', value: 'somesomesomehere' } objects in the "attributes" array of the "type" : "withdraw_rewards" object in the "events" array.
Currently this is the code I wrote to carry out my task:
getWithdrawnAmounts: async(del_addr_) => {
let withdrawnAmounts = [];
const res = await axios.get("some_url_that_uses_del_addr_");
res.data.tx_responses.forEach(txr => {
txr.logs.forEach(log => {
log.events.forEach(evnt => {
if (evnt.type == "withdraw_rewards") {
evnt.attributes.forEach(attr => {
if (attr.key == "amount") {
withdrawnAmounts.push(attr);
}
})
}
})
})
});
return withdrawnAmounts;
}
The code helps me to get what I need, but I was wondering if there is a better way to write my code so that I dont have to use so many nested .forEach methods. I was wondering if I should use .flat() or .flatMap() but I'm curious to know how would people approach this?
Thank you!
You are going to have to call some kind of iteration for each level you're going deeper.
Now, there is a more functional way to get the desired data, using flatMap and filter:
const data = { "tx_responses": [{ "logs": [{ "events": [{ "type": "coin_received", "attributes": [{ "key": "receiver", "value": "somesome" }, { "key": "amount", "value": "somesome" }]}, { "type": "transfer", "attributes": [{ "key": "recipient", "value": "somesome" }, { "key": "sender", "value": "somesome" }, { "key": "amount", "value": "somesome" }]}, { "type": "withdraw_rewards", "attributes": [{ "key": "amount", "value": "somesomesomehere" }, { "key": "validator", "value": "somesome" }]}]}]}]};
const result = data.tx_responses
.flatMap(r => r.logs
.flatMap(l => l.events.filter(e => e.type === 'withdraw_rewards')
.flatMap(e => e.attributes.filter(a => a.key === 'amount'))
)
);
console.log(result);
I am trying to the values from my data.json which consists of array of objects. I am trying to get the values by using map method on json data. My Json dat structure is like Array->Object->Array-Object([{[{}]}]). This is how the data is structured in Json. I have written down the Json data and logic to get the values down. Whenever I am trying to get the values from (inner array of object) I am ending up with undefined. Any one could assist me how to resolve this issue. Thanks in advance!
[
{
"key": "row-0",
"cells": [
{
"key": "cell-0",
"id": "ID-0",
"headerName": "Name",
"CustomerName": "ABC"
},
{
"key": "cell-1",
"id": "ID-1",
"headerName": "RegID",
"CustomerID": "P-01"
},
{
"key": "cell-2",
"id": "ID-2",
"headerName": "Detail",
"Deatil": "Abc"
}
]
},
{
"key": "row-1",
"cells": [
{
"key": "cell-1",
"id": "ID-1",
"headerName": "Name",
"CustomerName": "CDE"
},
{
"key": "cell-2",
"id": "ID-2",
"headerName": "RegID",
"CustomerID": "P-02"
},
{
"key": "cell-3",
"id": "ID-3",
"headerName": "Detail",
"Deatil": "CDE"
}
]
}
]
//Logic
{mockData.map((values, index) => {
console.log("VALUES", values);
return values.cells.map(({ headerName, ...rest }) => {
console.log("JSON", JSON.stringify(rest));
console.log("REST", rest.CustomerName);---> getting undefined(I tried many approach everything is giving me undefined)
});
})}
I have created an example for you
As mentioned in the above comment.. elements without customerName will give undefined.
let mockData = [{
"key": "row-0",
"cells": [{
"key": "cell-0",
"id": "ID-0",
"headerName": "Name",
"CustomerName": "ABC"
},
{
"key": "cell-1",
"id": "ID-1",
"headerName": "RegID",
"CustomerID": "P-01"
},
{
"key": "cell-2",
"id": "ID-2",
"headerName": "Detail",
"Deatil": "Abc"
}
]
},
{
"key": "row-1",
"cells": [{
"key": "cell-1",
"id": "ID-1",
"headerName": "Name",
"CustomerName": "CDE"
},
{
"key": "cell-2",
"id": "ID-2",
"headerName": "RegID",
"CustomerID": "P-02"
},
{
"key": "cell-3",
"id": "ID-3",
"headerName": "Detail",
"Deatil": "CDE"
}
]
}
];
mockData.map((values, index) => {
console.log("VALUES", values);
return values.cells.map(({
headerName,
...rest
}) => {
console.log("JSON",rest);
console.log("Key:", rest.key);
console.log("ID:", rest.id);
console.log("CustomerName:", rest.CustomerName ? rest.CustomerName : 'NA' );
});
})
I have an object that looks like the following {key: id numbers}
var obj = {
"c4ecb": {id: [3]},
"a4269": {id: [34,36]},
"d76fa": {id: [54,55,60,61]},
"58cb5": {id: [67]}
}
How do I loop each above id in the following array, and return the label?
var response =
{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}
Finally, what I want to do is look up the key and return a string of id values.
For example, input c4ecb and output strawberry. Input a4269 and output lettuce, radish. Input d76fa and output "spaghetti, rigatoni, lasagna, fettuccine"
I think to join the multiple labels output into one string I could use something like
array.data.vegetables.map(vegetables => vegetables.value).join(', ')].toString();
So in the end I want to have something like
var fruits = [some code that outputs "strawberry"];
var vegetables = [some code that outputs "lettuce, radish"];
var pasta = [some code that outputs "spaghetti, rigatoni, lasagna, fettuccine"];
What I've tried so far:
The following loop will return the id only if there is one id to be called for: e.g. only in case one where {id: 3} but returns null in cases like {id: 34,36} (because it's looking for '34,36' in id, which doesn't exist - I need to look for each one individually.
response.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
Filter the response object to focus on the category that matches the id.
Map over the options array and select the items which appear in obj[id].
Finally convert the filtered results to a string.
See filteredLabelsAsString() function below for implementation.
var obj = {
"c4ecb": {"id": [3]},
"a4269": {"id": [34,36]},
"d76fa": {"id": [54,55,60,61]},
"58cb5": {"id": [67]}
}
var response =
[{
"success": true,
"data": [
{
"key": "c4ecb",
"name": "fruits",
"options": [
{
"label": "strawberry",
"id": 3
},
{
"label": "apple",
"id": 4
},
{
"label": "pineapple",
"id": 5
},
{
"label": "Other",
"id": 31
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "a4269",
"name": "vegetables",
"options": [
{
"label": "lettuce",
"id": 34
},
{
"label": "cucumber",
"id": 35
},
{
"label": "radish",
"id": 36
}
],
}
]
},
{
"success": true,
"data": [
{
"key": "d76fa",
"name": "pasta",
"options": [
{
"label": "spaghetti",
"id": 54
},
{
"label": "rigatoni",
"id": 55
},
{
"label": "linguine",
"id": 56
},
{
"label": "lasagna",
"id": 60
},
{
"label": "fettuccine",
"id": 61
}
],
}
]
}];
function filteredLabelsAsString(obj_key, obj, content=response) {
// sanity check: obj must contain obj_key
if (Object.keys(obj).includes(obj_key)) {
return content.filter((item) => {
// filter content using value of obj_key
return item.data[0].key == obj_key;
}).map((item) => {
// item : { success: true, data: [] }
// map over options array
return item.data[0].options.map((opt) => {
// option : {id, label}
// return the label if the id is in the obj object's list
if (obj[item.data[0].key].id.includes(opt.id))
return opt.label;
}).filter((label) => {
// filter out empty items
return label !== undefined;
});
}).join(",");
}
// if obj does not contain obj_key return empty string
return "";
}
console.log("fruits: " + filteredLabelsAsString("c4ecb", obj));
console.log("vegetables: " + filteredLabelsAsString("a4269", obj));
console.log("pasta: " + filteredLabelsAsString("d76fa", obj));
I am trying to change the values of my nested object by using the data from another object but for some reason it is never setting the value. If i put static text in there it works but just doesn't work if the data from my other object
const projectFormTypes = [
{
"type": "Theatrical",
"sections" : {
"project": {
"fields": [
{
"label": "Project Title",
"name": "title",
"required": true,
"type": "textbox",
"visible": true,
'value': ''
},
]
},
"participants": {
"fields": [
{
"label": "First Name",
"name": "firstName",
"required": false,
"type": "textbox",
"visible": true,
"value": "first name 1"
},
]
},
"earnings": {
"fields": [
{
"label": "Compensation Amount",
"name": "wages",
"prefix": "$",
"required": false,
"type": "textbox",
"visible": true,
"value": 100000
},
]
}
}
},
]
const projectData = [{"fileDetailRecordId":3,"detailRecordId":"341697P3","signatoryName":"comp 2","signatoryId":"comp sag","contract":"Theatrical","sagId":"aftra 2","title":"Project 2","principalPhotoDate":"2019-12-13","madeFor":"Interactive Media","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"In-Flight","commercialTitle":"Project 2","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"987654","firstName":"test","middleName":"test","lastName":"test","loanOutNumber":"45687","loanOutName":"54854","performerType":"Background","performerCategory":"Dancer","paymentType":"Payroll","wages":"852963","subjectToPh":"852963","phContrib":"8529363","contribPercent":"10.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":1,"detailRecordId":"341697P1","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Network","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Phono Conversation","ssn":"456","firstName":"first name 1","middleName":"middle name 1","lastName":"last name 1","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Actor","paymentType":"Deferred","wages":"500","subjectToPh":"500","phContrib":"500","contribPercent":"1000.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":2,"detailRecordId":"341697P2","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Home Video","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"123","firstName":"last name 2","middleName":"last name 2","lastName":"last name 2","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Dance Coreographer","paymentType":"Deferred","wages":"800","subjectToPh":"800","phContrib":"800","contribPercent":"50.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"}]
const pp = Object.keys(projectFormTypes).forEach(function(r) {
for(let key in projectFormTypes[r].sections){
for(let o in projectFormTypes[r].sections[key].fields){
projectFormTypes[r].sections[key].fields[o].value = projectData[0][o.name];
}
}
});
console.log('result', projectFormTypes);
projectData[0][o.name]
should be
projectData[0][projectFormTypes[r].sections[key].fields[o].name]
o is the index in the fields array, and numbers don't have a name property. You want the name of the current element of the for loop.
But the code is simplified and less error prone if you use forEach() for all the nested loops.
const projectFormTypes = [{
"type": "Theatrical",
"sections": {
"project": {
"fields": [{
"label": "Project Title",
"name": "title",
"required": true,
"type": "textbox",
"visible": true,
'value': ''
}, ]
},
"participants": {
"fields": [{
"label": "First Name",
"name": "firstName",
"required": false,
"type": "textbox",
"visible": true,
"value": "first name 1"
}, ]
},
"earnings": {
"fields": [{
"label": "Compensation Amount",
"name": "wages",
"prefix": "$",
"required": false,
"type": "textbox",
"visible": true,
"value": 100000
}, ]
}
}
}, ]
const projectData = [{"fileDetailRecordId":3,"detailRecordId":"341697P3","signatoryName":"comp 2","signatoryId":"comp sag","contract":"Theatrical","sagId":"aftra 2","title":"Project 2","principalPhotoDate":"2019-12-13","madeFor":"Interactive Media","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"In-Flight","commercialTitle":"Project 2","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"987654","firstName":"test","middleName":"test","lastName":"test","loanOutNumber":"45687","loanOutName":"54854","performerType":"Background","performerCategory":"Dancer","paymentType":"Payroll","wages":"852963","subjectToPh":"852963","phContrib":"8529363","contribPercent":"10.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":1,"detailRecordId":"341697P1","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Network","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Phono Conversation","ssn":"456","firstName":"first name 1","middleName":"middle name 1","lastName":"last name 1","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Actor","paymentType":"Deferred","wages":"500","subjectToPh":"500","phContrib":"500","contribPercent":"1000.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":2,"detailRecordId":"341697P2","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Home Video","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"123","firstName":"last name 2","middleName":"last name 2","lastName":"last name 2","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Dance Coreographer","paymentType":"Deferred","wages":"800","subjectToPh":"800","phContrib":"800","contribPercent":"50.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"}]
projectFormTypes.forEach(function(type) {
Object.values(type.sections).forEach(function(section) {
section.fields.forEach(function(field) {
field.value = projectData[0][field.name];
});
});
});
console.log('result', projectFormTypes);