如何在TypeScript中为已有JSON数组内的对象添加键值对
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

