I know there are a lot of questions like this and this is probably a duplicate, but be sure, i tried every single solution provided to these questions and none of them worked for me.
Here's the thing:
I have an array of objects:
let data = [
{
id: 1,
year: 2022,
month: 11,
currentCount: 2460.9,
},
{
id: 2,
year: 2022,
month: 9,
currentCount: 2481.4,
},
{
id: 3,
year: 2022,
month: 2,
currentCount: 2521.1,
}
]
and i want to loop through the array and add a new property to each object. I tried many different ways (forEach, for-loop, etc) but my latest try was this one:
data.map((item, index) => {
if (prevCount === undefined) {
//do some things here
} else {
//do some things here
//the new property i want to add
let newProperty = "foo"
//some methods i tried
item.newProperty = "foo"
item[newProperty] = "foo"
let obj = {newProperty: "foo"}
let newObj = Object.assign(item, obj)
//do some things here
}
})
but in the end nothing happens. No error and no new property. I'm getting a bit crazy over this one, because it seems so simple...
Any help is appreciated
EDIT
After changing the map to this:
let newData = dataElec.map((item, index) => {
if (prevCount === undefined) {
prevCount = item.currentCount
return item
} else {
let meter = {foo: 'bar'}
return {...item, meter}
}
})
it is kind of working, but i get a weird object structure:
the object and properties (first red box) are not added by my code. i don't know where they come from. The content/properties of the object "_doc" (second red box) should be on the same level as the "meter" object.
I could work with a structure like this, but i would like a clean array. And I'm wondering how the other objects are getting into my array anyways...
so again, any help is appreciated. Thanks
CodePudding user response:
There may be a problem with prevCount
not being defined. Other than that, you're doing it right. Try logging data
after the map
call. However, when modifying items in an array directly, use forEach instead of map.
data.forEach(item => {
item.foo = 'bar'
})
Use map if you want a duplicate array with things changed. This returns a new array with the key 'foo' added to each object.
data.map(item => {
return { ...item, foo: 'bar' }
})
CodePudding user response:
let data = [
{
id: 1,
year: 2022,
month: 11,
currentCount: 2460.9,
},
{
id: 2,
year: 2022,
month: 9,
currentCount: 2481.4,
},
{
id: 3,
year: 2022,
month: 2,
currentCount: 2521.1,
}
];
data = data.map((item, index) => {return {...item,foo:"bar"}})
console.log(data);