Map an dynamic array in array js - javascript

I have an array(it isn't final version, the array is dynamic)
[{
"TemplateName": "C__01",
"Template": "<div><h1>Hello world!</h1><div id='C__01__body'></div></div>",
"TemplateBody": "body",
"TemplateChildren": [{
"TemplateName": "C__02",
"Template": "<p>Hello1</p>",
"TemplateBody": null,
"TemplateChildren": [{
"TemplateName": "C__03",
"Template": "<p>Hello2</p>",
"TemplateBody": null,
"TemplateChildren": [{
"TemplateName": "C__04",
"Template": "<p>Hello3</p>",
"TemplateBody": null,
"TemplateChildren": null
}, {
"TemplateName": "C__05",
"Template": "<p>Hello4</p>",
"TemplateBody": null,
"TemplateChildren": null
}]
}]
}]
}];
I'm not looking for a field, I just need to map each array in array

const parse = arr => {
arr.map(item => {
console.log(item);
if (item.TemplateChildren) {
parse(item.TemplateChildren);
} else {
return [];
}
});
}

Related

Add new property to react state

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.

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
])));

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

How do I avoid nested maps to get the values I need from nested arrays?

I am doing something like this to get the values I need:
tableRowsItems = data.softy.map(row =>
row.items.map(item => console.log('item', item)),
);
With that, I get something like in the picture below which is exactly what I need
My question is if that is the proper ES6 way to do it.
I am also using lodash if that helps.
This is how the json file looks without the map:
[
{
"ticketId": 67973802,
"account": null,
"items": [
{
"id": 11705294,
"billingItemId": 361643044,
"cancellationRequestId": 17289674,
"immediateCancellationFlag": true,
"scheduledCancellationDate": null,
"serviceReclaimStatusCode": "COMPLETE",
"billingItem": {
"description": "Storage as a Service",
"recurringFee": 0,
"id": 361643044
}
}
]
},
...
]
...
What I need is what you see on items key
Using ES6 you can easily do one line function to help you flatten the nested array by the items property via Array.reduce:
var tickets = [{ "ticketId": 67973802, "account": null, "items": [{ "id": 117052912, "billingItemId": 36164304123, }, { "id": 11705232, "billingItemId": 361643044, }] }, { "ticketId": 67973802, "account": null, "items": [{ "id": 117052945, "billingItemId": 361643046, }, { "id": 117052953, "billingItemId": 361643049, }] } ];
const pullBy = (arr, prop) => arr.reduce((r,c) => [...r[prop], ...c[prop]])
console.log(pullBy(tickets, 'items'))
Using lodash the best option is flatMap:
var tickets = [{ "ticketId": 67973802, "account": null, "items": [{ "id": 117052912, "billingItemId": 36164304123, }, { "id": 11705232, "billingItemId": 361643044, }] }, { "ticketId": 67973802, "account": null, "items": [{ "id": 117052945, "billingItemId": 361643046, }, { "id": 117052953, "billingItemId": 361643049, }] } ];
const result = _.flatMap(tickets, 'items')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
If I understand your question correctly, you're trying to extract all nested items from your array of ticket objects - in which case you can achieve this by mapping the input tickets to an array of items arrays, and then flatten the result to squish that down to a flat a array of item objects like so:
var output = input
.map(ticket => ticket.items) // Map each ticket to array of ticket items
.flat(); // Reduce array of item arrays to combined array of items
var input = [
{
"ticketId": 67973802,
"account": null,
"items": [
{
"id": 11705294,
"billingItemId": 361643044,
"cancellationRequestId": 17289674,
"immediateCancellationFlag": true,
"scheduledCancellationDate": null,
"serviceReclaimStatusCode": "COMPLETE",
"billingItem": {
"description": "Storage as a Service",
"recurringFee": 0,
"id": 361643044
}
}
]
},
{
"ticketId": 67973802,
"account": null,
"items": [
{
"id": 11705294,
"billingItemId": 361643044,
"cancellationRequestId": 17289674,
"immediateCancellationFlag": true,
"scheduledCancellationDate": null,
"serviceReclaimStatusCode": "COMPLETE",
"billingItem": {
"description": "Storage as a Service",
"recurringFee": 0,
"id": 361643044
}
}
]
}
];
var output = input.map(ticket => ticket.items).flat();
console.log(output);
Lodash has flatMap (the native JS version is not yet supported on all browsers) and you can use it as:
var items = _.flatMap(tickets, t => t.items);
to get all items from all tickets in a single 1-d array:
var tickets = [{
"ticketId": 67973802,
"account": null,
"items": [{
"id": 117052912,
"billingItemId": 36164304123,
}, {
"id": 11705232,
"billingItemId": 361643044,
}]
},
{
"ticketId": 67973802,
"account": null,
"items": [{
"id": 117052945,
"billingItemId": 361643046,
}, {
"id": 117052953,
"billingItemId": 361643049,
}]
}
];
var items = _.flatMap(tickets, t => t.items);
console.log(items);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Above answers will help you to achieve the goal but we use .map when we want to return something from the looping, otherwise you should use forEach.
I know it is really irrelevent to given questions but still. wanted to put it into the thread.

Categories