I understand the source of the problem, but I'm just a bit stuck on how to resolve it.
I'm doing something like items.map(item, index), but in the browser console I get an entire object. This object has another object within it called data, and that's where I'm trying to apply the map function, since I understand it only works on arrays. The object looks like this:
{
"data":[
{"id":"1","name":"a","description":"aaaaaa"},
{"id":"2","name":"b","description":"bbbbbb"},
{"id":"3","name":"c","description":"cccccc"}
]
}
But when I try to do items.data.map, I get the error property 'data' does not exist on type 'Item[]', which is true. It only shows up in the browser console.
What am I missing and is it possible to resolve it without adding a data property?
Thank you!
data is an array, so to access its inner content, you have to apply map() in a nested manner:
items.map((item) => item.data.map((data) => /* you can access the inner data here */));
items.data.map doesn't work because the key is "data", not data
Your object keys should not be strings:
{
data: [
{id: 1, name: "a", description: "aaaaaa"},
{id: 2, name: "b", description: "bbbbbb"},
{id: 3, name: "c", description: "cccccc"}
]
}
Then you can do:
items.data.map((item, index) => ...
Related
I'm looking for a way to access a nested array in my data structure.
My objects in my data array look like this :
{
name: name,
logo: url,
categories: [
{
name: Entertainment,
slug: "entertainment
},
{
name: Kids,
slug: kids
},
]
}
In the Docs I states that I need to use columnHelper.accessor to extract primitive values for each item in your data array.
My question is : how can I configure my accessor on "categories" to display both of them in my cell (using map I guess) ?
First, you don't need to use columnHelper; you can, for convenience (well, type safety, mostly).
You can do something like this:
cell: info => {
const value = info.getValue() as YourCategoryType[]; //casting may not be required here
return <>{value.map(v => <p key={v.slug}>{v.name}</p>)}</>
},
I am having trouble on posting the lists of data in my table, I hope you guys can help me with this issue, this is the error i am getting Error: Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.
const columns = [
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
}
},
{
name: "dateregistered",
label: "Date Registered",
options: {
filter: true,
sort: false,
}
},
{
name: "department",
label: "Department",
options: {
filter: true,
sort: false,
}
},
];
const data = [
posts.map(post => [{name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}])
];
return (
<>
<MUIDataTable
title={"Deactivated Users"}
data={data}
columns={columns}
options={options}
/>
</>
)
I see two problems in your data constant. The first one, the .map method returns an array, so there is no need to wrap that value inside an array keys []. The other problem is that you are wrapping the .map return state object in array keys too, that is why the error of creating an object is displayed, because you are returning arrays inside the main mapped array [[{ name: ... }], [{ name: ... }]].
So basically the solution for your issue would be:
const data = posts.map(post => ({name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}))
Where the parenthesis allows the map method to directly return the object.
The issue is that data is being created as an array in an array in an array. This is why when you try const data = posts.map(post => ...) the error persists, as there is still an array in an array. After you try the above, also re-write
post => [{name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}]
to
post => ({name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'})
(Changing the square brackets to round)
P.S When you map over posts to build the data, you build a object with the the key "name" and the value "'post.firstname'". That value is a string literal and not accessing some other JS object (It will make "post.firstname" the value for all the post's. Same goes for the other keys.
I'm stuck since a while trying to access a nested array inside another array after filtering it by an id. To be clear, this is the mock data I have:
bundleSets: [
{
id: 1,
title: "bundle set 1",
bundles: [
{
bundleTitle: "bundle 1",
content:[]
},
{
bundleTitle: "bundle 2",
content:[]
}
]
},
{ id:2,
title: "bundle set 2",
bundles: [
{bundleTitle: "ciaopao", content:[]}
]
},
{ id:3,
title: "bundle set 3",
bundles: [
{bundleTitle: "ciapo", content:[]}
]
}
]
Now I need to filter each bundleSets by id, and then access the bundles array inside and mapping those elements. This is what I tried to do:
const [key,setKey]=useState(1)
const [bundles,setBundles]=useState([])
useEffect(()=>{
const filteredBundles = bundleSets && bundleSets.filter(bundleSet=>bundleSet.id==key).map(filteredBundles=>{
return filteredBundles.bundles
})
setBundles(filteredBundles)
},[key])
Now If I try mapping the new state I can see on the console.log a weird [Array(1)] instead of the usual [{}] and I can't render it to the page. Where am I getting wrong with this?
Array.prototype.map returns an array and the callback you're passing to the map method returns filteredBundles.bundles which is an array. So, you get an array of arrays. filteredBundles is a confusing name, btw.
Since you're looking up the bundle by id and the ids are unique in the bundleSets array, you can use Array.prototype.find to find the bundle set by id and then get the bundle array. You can return an empty array if find returns undefined (if the key is not found).
const bundles = bundleSets?.find(set => set.id === key)?.bundles || []
I am trying to access a nested object in ReactJS. This is what the object looks like:
const characteristics = [
{ id: "geo", content: 'Geopolitical' },
{ id: "dog", content: 'Dog Loving' },
];
const starterColumns = {
"1": {
name: 'I am',
items: characteristics
},
"2": {
name: 'fullstack developer',
items: []
}
}
const [columns, setColumns] = useState(starterColumns);
This is the error I get when I try to console.log(columns['2']['items']['0']['id']):
TypeError: Cannot read property 'id' of undefined
Does this have to do with the fact that I am working with a stateful variable? Is something funky going on with the nested objects? Thanks for the help!
EDIT
The problem was that there was no object in the column so I had no object to access. Now the problem outstanding is how do I fill that void without displaying a new drag and drop piece. Thanks for helping!
EDIT
I used a try/catch statement to check the object so if it is empty, nothing happens.
Use try catch only for errors that you can't handle
To access an element use dot notation whenever it's possible instead of using bracket notation []
When there is an empty array in the items you can't access to the id you will get an error so the solution is to check if the array is not empty
columns['2'].items.length > 0
To access the first element of an array you have to use [0] instead of ['0']
try this solution
if (columns['2'].items.length > 0) {
console.log(columns['2'].items[0].id)
}
I have an array that looks like this:
[{
LocalBond:"0",
LocalCash:"2.42",
LocalEquity:"0",
ForeignEquity: "4",
...
}]
What I want it look like:
[{
Source: "LocalBond",
Value: "0"
},
Source: "LocalCash",
Value: "2.42"
},
Source: "LocalEquity",
Value: "0"
},
{...}
]
I want to turn a single object into many objects. I also need the exclude the 'ForeignEquity' result.
I tried using _.map, and returning the fields I want, but I am struggling a bit. Am I on the right track? When I pass more than one parameter into my function, I don't get the desired result.
The most simple code is pure javascript:
Using for..in access to the property of the object, and inside of the for loop build the array.
http://www.w3schools.com/jsref/jsref_forin.asp
Example:
https://jsfiddle.net/jewrsL8a/5/
var collection = [{
LocalBond:"0",
LocalCash:"2.42",
LocalEquity:"0",
ForeignEquity: "4"
}];
var result = [];
for (var property in collection[0]) {
if(property!=='ForeignEquity'){
result.push({'Source': property, 'Value': collection[0][property]});
}
}
console.log(result);