I'm working on a project where I want abbreviated state variables to become the full name of the state. I have been trying to do this using forEach()
, but I keep getting undefined when I console.log
it.
This is what I have:
console.log(orderLocationUS.forEach((state) => {
if (state._id === 'NY'){
state._id = 'New York'
}}))
where orderLocationUS is equal to:
[
{ _id: 'NY', count: 1, totalSales: 20 },
{ _id: 'New Jersey', count: 1, totalSales: 30 },
{ _id: 'New York', count: 31, totalSales: 627 }
]
I would really appreciate any help or advice on how to fix this or what I am doing wrong. Thank you!
CodePudding user response:
orderLocationUS = [{
_id: 'NY',
count: 1,
totalSales: 20
}, {
_id: 'New Jersey',
count: 1,
totalSales: 30
}, {
_id: 'New York',
count: 31,
totalSales: 627
}]
console.log(orderLocationUS.map((state) => {
if (state._id === 'NY') {
state._id = 'New York'
}
return state
}))
Hope this helps!
CodePudding user response:
No. You are wrong.
.forEeach
method returns undefined
. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#return_value
You should not modify the orderLocationUS
state. You should use map
to create a new array like:
orderLocationUS.map((location) => {
if (!(location._id === 'NY')) {
return location;
}
return {
...location,
_id: 'New York',
}
})
If you want to modify the object, you have to forEach
first and put the console.log(orderLocationUS)
in the next line because forEach returns undefined
as said. But I never do this