我正在嘗試在數組中插入新的鍵,這些鍵基本上是從父數組中提取的。我找不到僅僅通過將新密鑰插入到提取的數組中就會導致商店內的主數組發生變化的原因。
這是我嘗試在自訂數組中新增鍵值對的方法
const array = [{"integrationTypeId":1,"type":"aptus","fields":[{"name":"base_url"},{"name":"hash_key"}]}] function runArray(){ let connectorObject= {} let newArray if (array.length > 0) { connectorObject = array.find( (c) => c.integrationTypeId === 1, ); newArray = connectorObject.fields newArray !== undefined && newArray.map((object) => { return Object.assign(object, { inputType: "textField", value: object.name, }) }) } console.log(JSON.stringify(newArray)) console.log(JSON.stringify(array)) } runArray();
以下是輸出:
控制台 1.:newArray
[{"name":"base_url","inputType":"textField","value":"base_url"},{"name":"hash_key","inputType":"textField","value":"hash_key"}]
控制台 2.:父數組
[{"integrationTypeId":1,"type":"aptus","fields":[{"name":"base_url","inputType":"textField","value":"base_url"},{"name":"hash_key","inputType":"textField","value":"hash_key"}]}]
是什麼讓它用 newArray 值進行修改。
甚至嘗試過: newArray.map(obj => ({ ...obj, [inputType]: "textField"}));
P粉1414555122024-04-04 15:32:25
重要的是要知道 Javascript 陣列和物件是透過引用傳遞的。這表示如果您修改數組或對象,它將反映在對該數組或對象的所有引用中。
在這種情況下,陣列-->物件-->陣列-->物件嵌套過多。因此,在提取時請確保建立一個新的陣列或物件。這裡我使用 ES6 ...
語法來建立一個新的陣列/物件。只需使用 =
即可複製其引用,從而反映變更。
下面的程式碼尚未優化,但我希望您明白這一點。
const array = [ { integrationTypeId: 1, type: "aptus", fields: [{ name: "base_url" }, { name: "hash_key" }], }, ]; function runArray() { let connectorObject = {}; let newArray = []; if (array.length > 0) { connectorObject = { ...array.find((c) => c.integrationTypeId === 1), //Creating brand new copy of array object fields: [...array.find((c) => c.integrationTypeId === 1).fields], //Creating brand new copy of fields array }; newArray = connectorObject.fields.map((field) => { //Creating brand new copy of fields array object return { ...field }; }); newArray.map((object) => { Object.assign(object, { inputType: "textField", value: object.name, }); }); } console.log(JSON.stringify(newArray)); console.log(JSON.stringify(array)); } runArray();