Add new property to react state - javascript

I am trying to add a new property to the state "initialTags". However, I do not know how to do that. I have tried to loop through the object to set the new property, however it didnt work. Also, the setState it all in a same function, but since setState is async, I am unable to setState on the same state after my first setState statement.
Initializing the state:
this.setState({ initialTags: [...tempTarget] }, () => console.log("initTags == ", this.state.initialTags));
Array of Object after setState:
[
{
"name": "AQS",
"projectId": "MTYzMDE1MzU3NjA3My10ZXN0MTA",
"projectName": null,
"isUserForAllProject": false
},
{
"name": "ED",
"projectId": null,
"projectName": null,
"isUserForAllProject": null
},
{
"name": "PAID",
"projectId": null,
"projectName": null,
"isUserForAllProject": null
},
{
"name": "QS",
"projectId": null,
"projectName": null,
"isUserForAllProject": null
}
]
The New property that needs to be added in the Object:
[
{
"name": "AQS",
"projectId": "MTYzMDE1MzU3NjA3My10ZXN0MTA",
"projectName": null,
"isUserForAllProject": false,
"return": []
},
{
"name": "ED",
"projectId": null,
"projectName": null,
"isUserForAllProject": null,
"return": []
},
{
"name": "PAID",
"projectId": null,
"projectName": null,
"isUserForAllProject": null,
"return": []
},
{
"name": "QS",
"projectId": null,
"projectName": null,
"isUserForAllProject": null,
"return": []
}
]
EDIT: SOLUTION
this.setState({ initialTags: [...tempTarget.map(item => ({...item, returnVal: []}))] })

this.setState((prev) => {
return {
...prev,
initialValues: prev.initialValues.map((item) => {
return {
...item,
returnValue: []
};
})
};
});
You shoudn't use return as it is a keyword.

Related

Remove object array duplicates and store non duplicate values in array

I need to merge an array of deliveries that have notes, how would I remove the duplicate object but still keep the note string and store it in an array for the non duplicated object
Key begin the delivery number:
"data": [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "",
"notes": "Note 1"
},
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": "Note 2"
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
into
"data": [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": ["Note 1", "Note 2"]
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
You can use Array.prototype.forEach() to loop over the notes array. If a note is encountered twice add their notes together.
const notes = [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "",
"notes": "Note 1"
},
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": "Note 2"
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
let filteredArray = []
notes.forEach(note => {
let noteFound = filteredArray.find(el => el.deliveryNumber === note.deliveryNumber)
if(noteFound){
// not first encounter
// add notes together
noteFound.notes.push(note.notes)
}else{
// first encounter
// make notes an array
note.notes = [note.notes||'']
filteredArray.push(note)
}
})
console.log(filteredArray)

Compare 3 arrray and find combination in javascript

I have 3 arrays as below
A: [
{
"label": "100Watts",
"value": "100Watts",
},
{
"label": "135Watts",
"value": "135Watts",
} ]
B: [
{
"label": "Large|100cm",
"value": "Large|100cm"
},
{
"label": "Small|125mm",
"value": "Small|125mm"
}
]
C: [
{
"label": "Black",
"value": "Black",
},
{
"label": "Black",
"value": "Black",
}
]
I have one master array as below
result:[
{
"x_powerConsumption": "100Watts",
"x_size": "Small|125mm",
"x_color": "Black",
},
{
"x_powerConsumption": "135Watts",
"x_size": "Large|100cm",
"x_color": "Black",
}
]
My code as below
let newArray = A.filter(o1 => result.some(o2 => o1.label === o2.x_size));
let newArray2 = B.filter(o1 => result.some(o2 => o1.label === o2.x_powerConsumption));
this.setState({selectedVarientOne: newArray[0].label, selectedVarientTwo:newArray2[0].label})
But my requirement is i need combination as below like
Output : Black --> 100Watts --> Small|125mm
But as per my above code it is coming like
Black --> 100Watts --> Large|100mm
Can anyone tell me how i can solve this?
Ok, I'm assuming that you want to match the array of objects to the main object
I just use a nest of for loops to see if values from an array(A,B, or C) match up with values from the main object(result) from only the important keys in the result object of course
var A=[{"label":"100Watts","value":"100Watts"},{"label":"135Watts","value":"135Watts"}]
var B=[{"label":"Large|100cm","value":"Large|100cm"},{"label":"Small|125mm","value":"Small|125mm"}]
//now for function to correlate data(sry for late answer was afk lol)
function attribute(arr,result){
const necessary_keys=["x_powerConsumption","x_size","x_color"]
var toReturn=[] //array with output to return
for(let i=0;i<arr.length;i++){
var arrValues=Object.values(arr[i]) //eg: A[0] would be ["100Watts","100Watts"]
for(let j=0;j<result.length;j++){
var resultValues=Object.keys(result[j])
.filter(key=>necessary_keys.includes(key))
.map(key=>result[j][key]) //result[0] would be ["100Watts","Small|125mm","Black"]
if(resultValues.some(value=>arrValues.includes(value))){
toReturn[i]=resultValues //["100Watts","Small|125mm","Black"] for arr[0]
}
}
}
return toReturn //all indexes with undefined dont correlate with result in any of its values
}
//now to use the function
let newArray=attribute(A,result)
let newArray2=attribute(B,result)
console.log("values from A:",newArray)
console.log("values from B:",newArray2)
<script>
var result=[
{
"dynamicPropertyMapLong": {
"sku-Equipment_x_color": 1,
"sku-Equipment_x_size": 1,
"sku-Equipment_x_powerConsumption": 3
},
"x_UAE_installationPrice": 0,
"bundleLinks": [],
"largeImage": null,
"smallImage": null,
"listVolumePrice": null,
"onlineOnly": false,
"listPrices": {
"aed": 100,
"loyaltyProgram": null
},
"configurationMetadata": [],
"largeImageURLs": [],
"x_skuCreationDate": null,
"productLine": null,
"listVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"derivedSalePriceFrom": "aed",
"model": null,
"x_powerConsumption": "100Watts",
"barcode": null,
"salePriceEndDate": null,
"images": [],
"unitOfMeasure": null,
"primaryMediumImageURL": null,
"dynamicPropertyMapBigString": {},
"active": true,
"x_promotionDetails": "5 Percent Off: 5OFF5",
"thumbImageURLs": [],
"mediumImageURLs": [],
"primarySourceImageURL": null,
"x_description": null,
"sourceImageURLs": [],
"primarySmallImageURL": null,
"x_autoShipPrice": 0,
"productFamily": null,
"primaryThumbImageURL": null,
"nonreturnable": false,
"x_loyaltyLevel": "LEVEL2",
"displayName": "Three variant sku1",
"salePrices": {
"aed": null,
"loyaltyProgram": null
},
"primaryFullImageURL": null,
"productListingSku": null,
"primaryLargeImageURL": null,
"derivedOnlineOnly": false,
"smallImageURLs": [],
"thumbnailImage": null,
"saleVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"x_size": "Small|125mm",
"saleVolumePrice": null,
"salePriceStartDate": null,
"quantity": null,
"salePrice": null,
"fullImageURLs": [],
"x_isonSale": "Y",
"variantValuesOrder": {},
"x_color": "Black",
"soldAsPackage": true,
"listingSKUId": null,
"x_SAR_installationPrice": 0,
"repositoryId": "300003-1",
"derivedListPriceFrom": "aed",
"x_installationPrice": 0,
"x_costPrice": null,
"configurable": false,
"listPrice": 100
},
{
"dynamicPropertyMapLong": {
"sku-Equipment_x_color": 1,
"sku-Equipment_x_size": 2,
"sku-Equipment_x_powerConsumption": 1
},
"x_UAE_installationPrice": 0,
"bundleLinks": [],
"largeImage": null,
"smallImage": null,
"listVolumePrice": null,
"onlineOnly": false,
"listPrices": {
"aed": 135,
"loyaltyProgram": null
},
"configurationMetadata": [],
"largeImageURLs": [],
"x_skuCreationDate": null,
"productLine": null,
"listVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"derivedSalePriceFrom": "aed",
"model": null,
"x_powerConsumption": "135Watts",
"barcode": null,
"salePriceEndDate": null,
"images": [],
"unitOfMeasure": null,
"primaryMediumImageURL": null,
"dynamicPropertyMapBigString": {},
"active": true,
"x_promotionDetails": "5 Percent Off: 5OFF5",
"thumbImageURLs": [],
"mediumImageURLs": [],
"primarySourceImageURL": null,
"x_description": null,
"sourceImageURLs": [],
"primarySmallImageURL": null,
"x_autoShipPrice": 0,
"productFamily": null,
"primaryThumbImageURL": null,
"nonreturnable": false,
"x_loyaltyLevel": "LEVEL2",
"displayName": "sku3",
"salePrices": {
"aed": null,
"loyaltyProgram": null
},
"primaryFullImageURL": null,
"productListingSku": null,
"primaryLargeImageURL": null,
"derivedOnlineOnly": false,
"smallImageURLs": [],
"thumbnailImage": null,
"saleVolumePrices": {
"aed": null,
"loyaltyProgram": null
},
"x_size": "Large|100cm",
"saleVolumePrice": null,
"salePriceStartDate": null,
"quantity": null,
"salePrice": null,
"fullImageURLs": [],
"x_isonSale": "Y",
"variantValuesOrder": {},
"x_color": "Black",
"soldAsPackage": true,
"listingSKUId": null,
"x_SAR_installationPrice": 0,
"repositoryId": "300003-3",
"derivedListPriceFrom": "aed",
"x_installationPrice": 0,
"x_costPrice": null,
"configurable": false,
"listPrice": 135
}
]
</script>
Assuming the other answer is correct, here is a shorter version:
result.map(({x_powerConsumption, x_size, x_color}) => ([
A.find(el => el.label === x_powerConsumption).value,
B.find(el => el.label === x_size).value,
C.find(el => el.label === x_color).value
]))
Example:
const A = [{ "label": "100Watts", "value": "100Watts" }, { "label": "135Watts", "value": "135Watts" }];
const B = [{ "label": "Large|100cm", "value": "Large|100cm" }, { "label": "Small|125mm", "value": "Small|125mm" }];
const C = [{ "label": "Black", "value": "Black" }, { "label": "Black", "value": "Black" }];
const result = [
{ "x_powerConsumption": "100Watts", "x_size": "Small|125mm", "x_color": "Black" },
{ "x_powerConsumption": "135Watts", "x_size": "Large|100cm", "x_color": "Black" }
];
console.log(result.map(({x_powerConsumption, x_size, x_color}) => ([
A.find(el => el.label === x_powerConsumption).value,
B.find(el => el.label === x_size).value,
C.find(el => el.label === x_color).value
])));

Property 'emailAddress' does not exist on type 'BaseModel'.ts

I have a feature that calls the api from the service , Now I wanted to do for each on the res.items and check the emailAddress but I cant loop through it and I am receiving an error Property 'emailAddress' does not exist on type 'BaseModel'.ts which I dont understand on why.
What seem to be the issue that causes this one ? why is that the for each not working ? Any ideaS?
this is the sample data from the _transactionUserPageEvent
#Component A service
getUserProfileTableDropdown(
id: number,
page: number,
pageSize: number,
searchString: string,
sortKey: string[],
sortOrder: string[]
): Observable<PagedModel> {
const params = new HttpParams()
.set('id', id.toString())
.set('page', page.toString())
.set('pageSize', pageSize.toString())
.set('searchString', searchString)
.set('sortKey', JSON.stringify(sortKey) || '')
.set('sortOrder', JSON.stringify(sortOrder) || '');
return this.httpRequestService.get<PagedModel>(
`${apiBaseUrl}/table/profiles`,
params
);
}
#Component A TS Code
private _transactionUserPageEvent() {
this.isTransactionUserLoading = true;
this.transactionUserTable.data = [];
this._userProfileService.getUserProfileTableDropdown(
this.accountId,
this.transactionUserTable.pageIndex + 1,
this.transactionUserTable.pageSize,
this.searchTransactionUserInput.nativeElement.value,
this.transactionUserTable.sortParams,
this.transactionUserTable.sortDirs
)
.pipe(
finalize(() => this.isTransactionUserLoading = false)
)
.subscribe({
error: err => this._notificationService.showError(err),
next: res => {
console.log("new users" , this.selectedNewUser)
this.transactionUserTable.totalElements = res.totalItemCount;
this.transactionUserTable.data = res.items as UserProfileDropdownDto[];
this.totalData = res.totalItemCount;
this.currentDisplayedData = res.lastItemOnPage;
res.items.forEach(item => {
if(item.emailAddress && selectedNewUser.findIndex(x => x.emailAddress === item.emailAddress) !== -1){
item.checked = true;
}
});
},
complete: noop
});
}
#base-model.ts
export class BaseModel {
// createdStr: string;
// createdByUser: AuditUser;
// modifiedStr: string;
// modifiedByUser: AuditUser;
}
export class PagedModel {
firstItemOnPage: boolean;
lastItemOnPage: boolean;
totalItemCount: number;
items: BaseModel[];
constructor(isFirstPage: boolean, isLastPage: boolean, totalItems: number, itemList: BaseModel[]) {
this.firstItemOnPage = isFirstPage;
this.lastItemOnPage = isLastPage;
this.totalItemCount = totalItems;
this.items = itemList;
}
}
#dto user code
export class UserProfileDropdownDto {
id: number;
fullName: string;
roleDisplay: string;
firstName:string;
lastName:string;
isChecked: boolean = false;
}
I'm not sure, about the behavior of your task, but I assumed that you want to fill a dropdown from API response right?
For that you created this model UserProfileDropdownDto & you want to fill this model as an Array from API response, after that you may consume this inside your html,
By Keeping this scenarios in my mind, this below solution may help you
Please update your UserProfileDropdownDto model like below
export class UserProfileDropdownDto extends BaseModel {
id: number;
fullName: string;
roleDisplay: string;
firstName:string;
lastName:string;
isChecked: boolean = false;
emailAddress: string;
....
}
Just make sure that your UserProfileDropdownDto model, must has the properties of API response.
Now make correction in your PagedModel model like this,
export class PagedModel {
firstItemOnPage: boolean;
lastItemOnPage: boolean;
totalItemCount: number;
items: UserProfileDropdownDto[];
constructor(
isFirstPage: boolean,
isLastPage: boolean,
totalItems: number,
itemList: UserProfileDropdownDto[]
) {
this.firstItemOnPage = isFirstPage;
this.lastItemOnPage = isLastPage;
this.totalItemCount = totalItems;
this.items = itemList;
}
On Based of your comment! I have write down solution for another problem
Current Result
let data = {
"id": 0,
"name": "adas",
"description": "dasdas",
"status": "",
"teamMembersDto": [
{
"id": 120098,
"fullName": "xsc#gmail.com xsc#gmail.com",
"roleDisplay": null,
"firstName": "xsc#gmail.com",
"lastName": "xsc#gmail.com",
"emailAddress": "xsc#gmail.com",
"phoneNumber": "12",
"companyName": "xsc#gmail.com",
"title": "xsc#gmail.com",
"lastLogin": null,
"createdDate": "09/08/2021 7:44:56 am",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null
},
{
"id": 40091,
"fullName": "yukre#gmail.com yukre#gmail.com",
"roleDisplay": null,
"firstName": "yukre#gmail.com",
"lastName": "yukre#gmail.com",
"emailAddress": "yukre#gmail.com",
"phoneNumber": "232423",
"companyName": "yukre#gmail.com",
"title": "3434",
"lastLogin": null,
"createdDate": "06/08/2021 12:35:32 pm",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null
}
],
"accountId": 4
}
Expected Result
let data = {
"id": 0,
"name": "adas",
"description": "dasdas",
"status": "",
"teamMembersDto": [
{
"id": 0,
"fullName": "xsc#gmail.com xsc#gmail.com",
"roleDisplay": null,
"firstName": "xsc#gmail.com",
"lastName": "xsc#gmail.com",
"emailAddress": "xsc#gmail.com",
"phoneNumber": "12",
"companyName": "xsc#gmail.com",
"title": "xsc#gmail.com",
"lastLogin": null,
"createdDate": "09/08/2021 7:44:56 am",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null,
"memberId": 120098
},
{
"id": 0,
"fullName": "yukre#gmail.com yukre#gmail.com",
"roleDisplay": null,
"firstName": "yukre#gmail.com",
"lastName": "yukre#gmail.com",
"emailAddress": "yukre#gmail.com",
"phoneNumber": "232423",
"companyName": "yukre#gmail.com",
"title": "3434",
"lastLogin": null,
"createdDate": "06/08/2021 12:35:32 pm",
"isVerified": false,
"roleDto": null,
"status": "Active",
"securityRole": "Unlicensed User",
"lastLoggedIn": "",
"teamCount": 0,
"transactionRoleList": null
"memberId": 40091
}
],
"accountId": 4
}
Solution
data.teamMembersDto = data.teamMembersDto.map((item) => {
let id = item.id;
return {
...item,
id: 0,
memberId: id
}
});

How to display nested array of objects from REST call in different sections of the page?

I have a REST call which returns different sets of result. Each data set contains data for different parts of the page. It contains nested array of objects and I am not sure how do I easily display the name and value pairs from the rest call to my page depending on the certain section.
Here's what the REST call response looks like:
{
"dstrSpecificHelpRs": [
{
"row": [
{
"name": "HELP_TEXT_TITLE_NM",
"value": "TestAgain and again and again and again andagain50",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "HELP_TEXT_ID",
"value": "100114",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "Help",
"value": "Help",
"link": {
"exists": true,
"linkType": "url",
"linkId": "www.google.com"
}
}
]
},
{
"row": [
{
"name": "HELP_TEXT_TITLE_NM",
"value": "Testing Helpline Page and 2301 DisasterONLY",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "HELP_TEXT_ID",
"value": "100174",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "Help",
"value": "Help",
"link": {
"exists": true,
"linkType": "url",
"linkId": "www.google.com"
}
}
]
}
],
"rgstInfoRs": [
{
"row": [
{
"name": "PREFIX_NM",
"value": "MS",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "FST_NM",
"value": "MITZI",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
}
]
}
],
"insSettlementRs": [
{
"row": [
{
"name": "ON_FILE",
"value": "0",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
}
]
}
],
"dstrOptionRs": [
{
"row": [
{
"name": "DSTR_OPTION",
"value": "1",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "HELPLINE_AREA_CD",
"value": "818",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "HELPLINE_PHN_NR",
"value": "5055511",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
}
]
}
],
"correspondenceOutRs": [
{
"row": [
{
"name": "SUMMARY_CD_TX",
"value": "SUPER,SEAL,APPR_INTRO,APPROVAL,ECNA",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
}
]
},
{
"row": [
{
"name": "SUMMARY_CD_TX",
"value": "9069CL,SEAL",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "ASTN_PGM_CD",
"value": "MISC",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "GENERATED_DT",
"value": "2020-09-03 14:08:10.0",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
}
]
}
],
"statePhoneRs": [],
"insAssistanceRs": [
{
"row": [
{
"name": "DOC_ID",
"value": "",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
},
{
"name": "RGSN_ID",
"value": "370002900",
"link": {
"exists": false,
"linkType": null,
"linkId": null
}
}
]
}
]
}
and here's what I have working so far:
class App extends React.Component {
constructor(props) {
super(props);
this.setState = {
data: []
};
}
componentDidMount() {
fetch("https://demo3531217.mockable.io/getRegistrationData")
.then((res) => res.json())
.then((res) => {
const responseData = this.getPayloadObject(res);
this.setState({
data: responseData
});
})
.catch((error) => console.error(error));
}
getPayloadObject = (action) => {
console.log(action);
Object.keys(action).forEach((key) => {
if (typeof action[key] === "object") {
const payload = action[key];
let result = _.map(
payload,
(data, i) => {
const row = data["row"];
const rowData = _.map(row, (item) => {
return {
name: item.name,
value: item.value
};
});
console.log("rowData ", rowData);
},
[]
);
return result;
}
});
};
render() {
return (
<div>
<div>
<h1>Section 1</h1>
</div>
<div>
<h1>Section 2</h1>
</div>
</div>
);
}
}
if I wanted to display certain data for specific section how do I so in my page? Can someone please help?
link for sandbox can be found here: https://codesandbox.io/s/vibrant-sid-i140l?file=/src/App.js:75-1304
Let's try breaking the state into multiple sections. Something like this.
constructor(props) {
super(props);
this.state = {
dstrSpecificHelpRs: [],
rgstInfoRs: [],
insSettlementRs: [],
dstrOptionRs: [],
correspondenceOutRs: [],
statePhoneRs: [],
insAssistanceRs: []
};
}
Then, let's deconstruct the API response and set individual items in the state.
componentDidMount() {
fetch("https://demo3531217.mockable.io/getRegistrationData")
.then((res) => res.json())
.then((res) => {
// const responseData = this.getPayloadObject(res);
const {
dstrSpecificHelpRs,
rgstInfoRs,
insSettlementRs,
dstrOptionRs,
correspondenceOutRs,
statePhoneRs,
insAssistanceRs
} = res;
this.setState({
dstrSpecificHelpRs: dstrSpecificHelpRs,
rgstInfoRs: rgstInfoRs,
insSettlementRs: insSettlementRs,
dstrOptionRs: dstrOptionRs,
correspondenceOutRs: correspondenceOutRs,
statePhoneRs: statePhoneRs,
insAssistanceR: insAssistanceRs
});
})
.catch((error) => console.error(error));
}
Now all you have to do is find a way to loop through individual items in the state. Something like this
render() {
const dstrSpecificHelpRs = this.state.dstrSpecificHelpRs.map(row => row["row"]);
console.log("Sample = ", sample);
return (
<div>
<div>
<h1>Section 1</h1>
<div>
{dstrSpecificHelpRs.map(item => item.map(key => <p>{key.name}</p>))}
</div>
</div>
<div>
<h1>Section 2</h1>
</div>
</div>
);
}
This is by no means a perfect solution though. If you could change the response model, that would have been sweet!.

How do you render objects from json

I need to render some images from some json that I am being given. The code looks like
class App extends React.Component {
componentDidMount() {
$.get(
"url"
data => {
});
}
render() {
return React.createElement("div", null, "hello");
}}
ReactDOM.render(React.createElement(App, null), document.body);
"url" is the json that I have passed in (but I do not want to make it public). It looks similar to this:
{
"total_count": null,
"_links": {
"self": {
"href": ""
},
"next": {
"href": ""
}
},
"_embedded": {
"showorks": [{
"id": "",
"slug": "",
"created_at": "",
"updated_at": "",
"title": "",
"category": "",
"medium": ",
"date": "",
"dimensions": {
"in": {
"text": "",
"height": 70.9,
"width": 70.9,
"depth": null,
"diameter": null
},
"cm": {
"text": "180.1 × 180.1 cm",
"height": 180.1,
"width": 180.1,
"depth": null,
"diameter": null
}
},
"published": true,
"website": "",
"signature": "",
"series": null,
"prov": "",
"lit": "",
"hist": "",
"isst": "",
"additional_information": "",
"image_rights": "",
"blurb": "",
"unique": false,
"maker": null,
"icon": ,
"inquire": false,
"acquire": false,
"share": true,
"message": null,
"sell":,
"image_versions": ,
"_links": {
"thumbnail": {
"href": ""
},
"image": {
"href": "",
"templated": true
},
"partner": {
"href": ""
},
"self": {
"href": ""
},
"link": {
"href": ""
},
"genes": {
"href": ""
},
"rar": {
"href": ""
},
"cim": {
"href": ""
},
"coll": {
"href": ""
}
},
"_embedded": {
"editions": []
}
}, {
"id": "",
I need the thumbnail for each id but I'm not sure how to iterate through the json to pull out each thumbnail in react/javascript
First, I totally recommend you to use JSX syntax to use React better. To do that, you will need a few Javascript Array helper function and some methods.
As you can see below:
class App extends React.Component
{
componentDidMount()
{
// We could imagine the incoming JSON data
// const exampleJson =
// {
// elements:
// [
// { href: 'example1', text: 'link value', style: { height: '10px' } },
// ],
// };
// This fetch API will help you to get JSON from URL like JQuery $.get
const exampleJson = fetch('http://example.com/links.json')
.then(function(response)
{
return response.json(); // get the values of JSON as string type
})
.then(function(myJson)
{
return JSON.stringify(myJson); // convert the JSON data to javascript object
});
this.setState(exampleJson); // it's like this.setState({ elements: [array values] });
console.log(exampleJson); // to do debug of your JSON data
}
render()
{
// we getting the elements array from state object
// with object spread operator
const { elements } = this.state;
// get values all of your json array
// loop values to do React element
// return all new values to use loopAndSaveElements variable
const loopAndSaveElements = elements
.map(({ text, ...otherProps}) => React.createElement('a', otherItems, text));
// send return div of React as loopAndSaveElements as array children
return React.createElement("div", null, loopAndSaveElements);
}
}
By the way, i didn't run the snippet of example. But i hope it give you an information.
ES6+ Sources:
const
Array map
spread syntax
JSX syntax
fetch API

Categories