我試著做一些基本的事情。我有一個包含多個物件的陣列。我想在每個陣列物件中添加新的鍵值對。
我通過以下代碼嘗試了這個。
exports.addBuyOption = (arr) => {
var newArr=arr;
return new Promise((resolve, reject) => {
for (let i = 0; i < newArr.length; i ) {
newArr[i].name="new name" //updating the existing key value
newArr[i].canBuy=true //new key value
}
setTimeout(() => {
resolve(newArr);
}, 2000)
})
}
我添加了設定超時,因為我只是想確認回圈操作后是否回傳了承諾。此外,當代碼不與原始陣列一起運行時,我使用 newArr 名稱創建一個新變數,但代碼也不起作用。
exports.addBuyOption = (arr) => {
return new Promise((resolve, reject) => {
for (let i = 0; i < arr.length; i ) {
arr[i].name="new name" //updating the existing key value
arr[i].canBuy=true //new key value
}
resolve(arr);
})
}
使用此代碼,我能夠更新現有的鍵值,但無法添加任何新的鍵值。請讓我知道我做錯了什么。我試圖改變將鍵從點運算子添加到陣列索引到 Object.assign 的方法,但它們都不適合我。
uj5u.com熱心網友回復:
使用此代碼,我能夠更新現有的鍵值,但無法添加任何新的鍵值。
唯一的解釋是陣列中的物件已Object.preventExtensions應用于它們。這是一個例子:
function addBuyOption(arr) {
for (let i = 0; i < arr.length; i ) {
arr[i].name="new name" //updating the existing key value
arr[i].canBuy=true //new key value
}
return arr;
}
const arr = [
{name: "old name 1"},
{name: "old name 2"},
{name: "old name 3"},
].map(Object.preventExtensions);
console.log("Before:");
console.log(JSON.stringify(arr, null, 4));
addBuyOption(arr);
console.log("After:");
console.log(JSON.stringify(arr, null, 4));
.as-console-wrapper {
max-height: 100% !important;
}
(注意我取消了這個承諾,它在這段代碼中沒有做任何有用的事情。)
如果發生這種情況,則無法向物件添加屬性。但是您可以使用具有新屬性的物件副本創建一個新陣列:
function addBuyOption(arr) {
return arr.map(obj => ({
...obj, // Copy existing properties
name: "new name", // Set new value for existing property
canBuy: true, // Set new property
}));
}
const arr = [
{id: 1, name: "old name 1"},
{id: 2, name: "old name 2"},
{id: 3, name: "old name 3"},
].map(Object.preventExtensions);
console.log("Before:");
console.log(JSON.stringify(arr, null, 4));
const newArr = addBuyOption(arr);
console.log("After:");
console.log(JSON.stringify(newArr, null, 4));
.as-console-wrapper {
max-height: 100% !important;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430442.html
標籤:javascript mongodb 猫鼬
