[英]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.