You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为数组对象添加属性失败,修改map后结构异常,求解决方案

为对象数组添加新属性失败的问题

我知道有很多类似问题,这可能是重复提问,但我确实尝试了这类问题下的所有解决方案,均未奏效。

情况说明

我有一个对象数组:

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,
  }
]

我想要遍历数组,为每个对象添加一个新属性。尝试了多种方式(forEach、for循环等),最近一次尝试的代码如下:

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
    }
})

但最终没有任何效果,既无报错也未添加新属性。这看似简单的问题却让我十分困惑...


编辑补充

将map修改为以下写法后:

let newData = dataElec.map((item, index) => {
    if (prevCount === undefined) {
        prevCount = item.currentCount
        return item
    } else {
        let meter = {foo: 'bar'}
        return {...item, meter}
    }
})

情况有所好转,但出现了奇怪的对象结构:

  • 数组中出现了额外的未知对象(第一个红框标注内容)
  • 原本期望和meter处于同一层级的_doc对象内容,被嵌套在内部结构中(第二个红框标注内容)

我可以勉强使用这种结构,但更希望得到一个结构干净的数组,同时也想知道这些额外对象是如何进入数组的...

恳请各位帮忙解决,谢谢!


内容的提问来源于stack exchange,提问作者mattisvensson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:15:42