[英]How can I add new property to Object in Array
我有一個對象數組
var array = [ {type: 'news', id: 1}, {type: 'contacts', id: 7}, {type: 'messages', id: 11} ]
我需要決定可以向對象添加屬性和值。 定義向哪個對象添加屬性的對象,我有一個類型
就像是
function(arr = array, type = 'news', property = 'visibility ', value = 'yes') {
var obj = arr.find(item => item.type === type)
/* magic */
return result
}
result = [ {type: 'news', id: 1, visibility: 'yes'}, {type: 'contacts', id: 7}, {type: 'messages', id: 11} ]
簡單的答案是(如果您可以對現有對象進行變異):
obj[property] = value
如果不允許突變,則:
function(arr = array, type = 'news', property = 'visibility ', value = 'yes') {
return arr.map((item) => {
if(item.type === type) {
return {...item, [property]: value}
}
return item
})
}
假設數組可以包含多個object === type
,則可以使用forEach
和Object.assing
函數為每個匹配的對象設置新屬性。
這種方法會從原始數組中更改對象。
function findNSet(arr, type, property, value) { arr.forEach(o => { if (o.type === type) Object.assign(o, {[property]: value}); }); } let array = [{type: 'news', id: 1}, { type: 'contacts', id: 7}, { type: 'messages', id: 11}]; findNSet(array, 'news', 'visibility', 'yes'); console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.