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

如何在TypeScript中为已有JSON数组内的对象添加键值对

Solution to Add Key-Value Pairs to an Existing Object in a TypeScript Array

Alright, I see where you're going wrong here—your current code uses push() twice, which adds two separate objects to the array instead of updating the first one. Let's fix this with a few straightforward approaches:

1. Directly Modify the Existing Object in the Array

Once you've pushed the initial object into the array, you can access it via its index (since it's the first element, that's index 0) and add the new properties directly:

let someData : any [] = [];
// Push the initial object into the array
someData.push({ "a" : "a1", "b" : "b1" });
// Add new properties to the first (and only) object in the array
someData[0].c = "c1";
someData[0].d = "d1";

// Result: [{ "a": "a1", "b": "b1", "c": "c1", "d": "d1" }]

2. Create the Full Object Before Pushing

If you know all the properties upfront, you can just build the complete object first and push it into the array—no need to modify it later:

let someData : any [] = [];
// Push the fully formed object right away
someData.push({ "a" : "a1", "b" : "b1", "c" : "c1", "d" : "d1" });

3. Use Object Spread for Immutable Updates (Optional)

If you prefer not to mutate the original object (a common practice in state management), use the object spread operator to create a new merged object, then replace the array element:

let someData : any [] = [];
someData.push({ "a" : "a1", "b" : "b1" });

// Merge original properties with new ones into a new object
const updatedObject = { ...someData[0], c: "c1", d: "d1" };
// Replace the old object in the array with the updated version
someData[0] = updatedObject;

All these methods will give you the single updated object in the array you're aiming for, instead of adding a second separate object.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:32:14