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

如何在Dart中更新/转换数组内对象的值

在JavaScript中遍历对象数组并修改/添加属性(保留原属性)

需求:遍历一个对象数组,修改或添加指定属性,同时保留大多数原始属性不变。

实现代码

const trips = [
    { status: 1, name: "trip1", foo: "bar" }, 
    { status: 1, name: "trip2", foo: "bar" }, 
    { status: 3, name: "trip3", foo: "foobar" }
];

const formatedTrips = trips.map(trip => ({
    ...trip, // 展开原始对象,保留所有未被覆盖的属性
    status: 1, // 强制将所有项的status改为1
    foo: trip.foo === "bar" ? `${trip.name} bar` : "barbar" // 根据原foo值动态设置新值
}));

处理结果

// formatedTrips 的最终值:
[
    { status: 1, name: "trip1", foo: "trip1 bar" }, 
    { status: 1, name: "trip2", foo: "trip2 bar" }, 
    { status: 1, name: "trip3", foo: "barbar" }
]

核心要点

  • 使用Array.map()创建新数组,避免直接修改原数组
  • 对象展开运算符...trip快速复制原始对象的所有属性,无需手动逐个列举
  • 后续声明的属性会覆盖原始对象的同名属性,以此实现修改效果
  • 支持通过条件判断动态调整属性值,适配不同业务场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:09:32