簡體   English   中英

將鍵值(對象)對添加到數組中的所有對象

[英]Add key value (object) pair to all objects in array

我的問題與將鍵值對添加到數組中的所有對象有關

但是,當我嘗試分配對象而不是字符串,int等時,解決方案不起作用。

我試圖在map函數中創建新的鍵,但是它僅適用於非對象變量。

這有效

arrObjects.map(item => item.newKey = 'xxx')

這不是

var obj = { a: 'a', b: 'b', c: 'c' }
arrObjects.map(item => item.newKey = obj)

輸出:

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: 'a', b: 'b', c: 'c' } arrOfObj.map(item => item.newKey = obj); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您需要使用... (擴展運算符)

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: 'a', b: 'b', c: 'c' }; arrOfObj.forEach(item => item.newKey = {...obj}); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

或者,使用JSON

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: 'a', b: 'b', c: 'c' }; arrOfObj.forEach(item => item.newKey = JSON.parse(JSON.stringify(obj))); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您需要創建對象的副本。 默認情況下,對象被分配為參考。 這里...用於創建淺表副本

 var arrOfObj = [{name: 'eve'}, {name: 'john'}, { name: 'jane'}]; var obj = { a: 'a', b: 'b', c: 'c'} arrOfObj.forEach(item => (item.newKey = {...obj})); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以在這里看到一些用例

一種替代方法是使用Object.assign() 請記住,對象是通過引用的值復制的,這就是您的問題,而不是每個newKey都有一個新對象,您對同一個對象有多個引用。

 var arrOfObj = [ {name: 'eve'}, {name: 'john'}, {name: 'jane'} ]; var obj = { a: 'a', b: 'b', c: 'c' }; arrOfObj.map(item => item.newKey = Object.assign({}, obj)); console.log(arrOfObj); // After some modification. arrOfObj[0].newKey.a = "XXX" console.log(arrOfObj); 

您必須克隆該項目,將同一對象添加到多個屬性。

請參閱下面的內容。

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: "a", b: "b", c: "c" } arrOfObj.map(item => // clone the item item.newKey = JSON.parse(JSON.stringify(obj)) ); console.log(arrOfObj); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM