I'm trying to map over an array in State and display the object values for title, but I keep getting [object object]
.
The below code only returns the title values when displayed as a console.log. I'm not sure what I'm missing, but any tips would be appreciated!
// State
const [cart, setCart] = useState({
wasteContents: []
});
// Set State
setAnswers(prevAnswers => {
const wasteContents = prevAnswers.wasteContents;
const alreadyExists =
wasteContents.find(item => item.title === title) !== undefined;
if (!alreadyExists) {
wasteContents.push({
title,
quantity: 0,
});
}
return {
...prevAnswers,
wasteContents: wasteContents.map(item => {
if (item.title === title) {
return {
...item,
quantity,
};
}
return item;
}),
};
});
// Map
cart.wasteContents.map(items => {
return items.title; // [object object]
// return console.log(); // prints value of 'title'
});
// Data saved in state
State
:
{wasteContents: Array(3), wasteQuantity: "Singular …}
wasteQuantity
:
"Singular Item(s)"
wasteQuantityWeight
:
undefined
wasteContents
:
[{…}, {…}, {…}]
0
:
{quantity: 2, title: "Household Junk"}
1
:
{quantity: 1, title: "Furniture"}
2
:
{quantity: 1, title: "Appliances"}
CodePudding user response:
Your function with your input works fine as expected
let wasteContents = [{title: 'Household Junk', quantity: 1}, {title: '33Household Junk', quantity: 1}, {title: '22Household Junk', quantity: 1}]
const test = () => wasteContents.map(items => {
console.log(items)
return items.title;
});
test();
I see react tag in your component so I guess you are using this to render some components. You should update in this way
{cart.wasteContents.map(items =>
return ( <p>{items.title}</p> )
)}
CodePudding user response:
So in the end I've got this working by using return cart.wasteContents.map((item) => { return item.title; });
! The reason the previous answer didn't work was down to missing off the return
for the actual map function!