Map Array of Ints to Nested Array Access

How to map a nested array of objects, one child array item at a time, in react

One is able to provide a workable code using stack-snippets like below:

const demos = [

{id : '1',
name: 'name1',
dates: ['jan', 'feb', 'apr']
},
{id : '2',
name: 'name2',
dates: ['feb', 'may']
}

];

// const counts = ['0','1','2'];

function Test() {
const sortHelper = Object.fromEntries(("jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec")
.split(", ").map((m, idx) => ([m, idx])));

const transformArr = arr => (
[...arr].map(({name, dates}) => (
dates.map(month => ({ name, month }))
))
.flat()
.sort((a, b) => (sortHelper[a.month] - sortHelper[b.month]))
);
return (
<div>
{
transformArr(demos).map(({name, month}) => (
<div>{name}: {month}</div>
))
}
</div>
);
}

ReactDOM.render(
<div>
DEMO
<Test />
</div>,
document.getElementById("rd")
);
<div id="rd"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

Recursively map an array with unlimited number of nested arrays in React

const List = ({complete_data})=> {
return (
<ul className="list-disc">
{complete_data.map(x=> <Item key={x.id} data={x} />)}
</ul>
)
}

const Item = ({data})=> {
return (
<li className="ml-10">
{data.fullname}
{data.children.length > 0 && (
<ul className="list-disc">
{data.children.map((x)=> <Item key={x.id} data={x} />)}
</ul>
)}
</li>
)
}

Map nested array with JavaScript

features is an array and you need to access it using index

 u.features[i].geometry.coordinates[0]
^^^

const undergroundGeoJson =[{'type':'FeatureCollection','crs':{'type':'name','properties':{'name':'urn:ogc:def:crs:OGC:1.3:CRS84'}},'features':[{'type':'Feature','geometry':{'type':'Point','coordinates':[-0.278126,51.5025]},'properties':{'name':'ActonTown'}},{'type':'Feature','geometry':{'type':'Point','coordinates':[-0.263033174,51.50883531]},'properties':{'name':'ActonCentral'}},{'type':'Feature','geometry':{'type':'Point','coordinates':[-0.262879534,51.50856013]},'properties':{'name':'ActonCentral'}}],}];
const ret = undergroundGeoJson.map((u,i) => [ u.features[i].geometry.coordinates[0], u.features[i].geometry.coordinates[1],]);
console.log(ret);

Map over nested array of objects

the error you give is has the answer in it.

Each child in a list should have a unique key prop

you're already halfway there by extracting the index that holds the nested object.
Now you only have to add the property key={I} to your ul

const items = [
{
page_num: 1,
status: "PROCESSED",
table_text_data:[
{bottom:58, height:60, left:60, right:67, text:"recorded"},
{bottom:75, height:67, left:50, right:60, text:"symbolic"},
{bottom:80, height:80, left:77, right:89, text:"fever"},
]
},
{
page_num: 2,
status: "PROCESSED",
table_text_data:[
{bottom:58, height:60, left:60, right:67, text:"recorded"},
{bottom:75, height:67, left:50, right:60, text:"symbolic"},
{bottom:80, height:80, left:77, right:89, text:"fever"},
]
}
];

const ItemDisplay = (props) => (
<React.Fragment>
{props.items.map(item => (
<ul key={item.page_num}>
<li>page_num={item.page_num}</li>
<li>status={item.status}</li>
{item.table_text_data.map((c,i) => (
<ul key={i}>
<li>bottom={c.bottom}</li>
<li>height={c.height}</li>
<li>left={c.right}</li>
<li>right={c.left}</li>
<li>text={c.text}</li>
</ul>
))}
</ul>
))}
</React.Fragment>
);

ReactDOM.render(
<ItemDisplay items={items} />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Nested mapping with 2d arrays: I need the index of my outer arrays

The issue is that the 'y' is out of scope to the current function, so it can't 'see' the value. For this reason you need to work out how to make it available to the second function. The two approaches I see:

  • Make second function's map an inner operation, within twoDimensionalArray.map(function (row, y)
  • Find a way to pass 'y' to the second function

For the first approach:

var testArray = [[true, "random-string", 3],
["potato", false, 4],
[null, 4, 5]];

function twoDMap(twoDimensionalArray) {
return twoDimensionalArray.map(function (row, y) {
return row.map(function (row, x) {
console.log(cell, "location: ", x, y);
}
})
}

twoDMap(testArray);

Below takes the second approach, using the bind() function:

var testArray = [[true, "random-string", 3],
["potato", false, 4],
[null, 4, 5]];

function twoDMap(twoDimensionalArray, mapFunction) {
return twoDimensionalArray.map(function (row, y) {
return row.map(mapFunction.bind(this, y);
})
}

function logCells(cells) {
twoDMap(cells , function(y, cell, x) {
console.log(cell, "location: ", x, y);
})
}

logCells(testArray);

When binding a values to a function always remember the first parameter should correspond to how you wish to define this and then the subsequent parameters are provided as initial parameters to the function you are calling.

I should add that sometimes using the traditional for loops makes for more manageable code, and sometimes benefit from better performance. An alternative, using for loops:

var testArray = [[true, "random-string", 3],
["potato", false, 4],
[null, 4, 5]];

function twoDMap(twoDimensionalArray) {
for (var y=0; y<twoDimensionalArray.length; y++) {
for (var x=0; x<twoDimensionalArray[y].length; x++) {
console.log(twoDimensionalArray[y][x], "location: ", x, y);
}
}
}

twoDMap(testArray);

Mapping nested array inside mapped array in React JSX

The object passed into the callback function for the map, menuItem has the included property secondaries. You can use map on this property since secondaries is an array, simply place the map inside of your JSX.

<div
className="card-body collapse ml-5"
id={`${socialItem.primaryText}Submenu`}
>
<ul className="list-unstyled">
{menuItem.secondaries.map((subItem) => {
...
})

</ul>
</div>

P.S. you forgot to close your last div tag, and you have a second </li> instead of a </ul>



Related Topics



Leave a reply



Submit