Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
assign property to object in array

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: screenshot of array in console

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

almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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);
almost 4 years ago · Santiago Trujillo Relatório

0

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' }
})
almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda