[英]Append/Add the property to array of objects if match found using javascript
[英]How to add property to array of objects if not found in javascript
我想知道是否找不到属性只是添加到 javascript 中的 object 数组
在 arrobj 中,一个特定的 object 没有值属性,因此需要使用 javascript 添加
var arrobj=[
{id:1, name: "ram", value: 100},
{id:2, name: "ben", value: 100},
{id:3, name: "laks"}
]
Expected Output
[
{id:1, name: "ram", value: 100},
{id:2, name: "ben", value: 100},
{id:3, name: "laks", value: null}
]
我试过了
const result = arrobj.forEach(e=>{
if(!e.hasOwnProperty("value"){
e.value=null
}
});
您使用的方法中只有一个错字。 您错过了在 if 语句中关闭)
。 以下作品:
var arrobj=[ {id:1, name: "ram", value: 100}, {id:2, name: "ben", value: 100}, {id:3, name: "laks"} ] const result = arrobj.forEach(e=>{ if(.e.hasOwnProperty("value")){ e;value=null } }). console.log(arrobj)
这是使用 for 循环的方法。
var arrobj=[ {id:1, name: "ram", value: 100}, {id:2, name: "ben", value: 100}, {id:3, name: "laks"} ] for (var i = 0; i<arrobj.length;i++){ if (arrobj[i].id == undefined){arrobj[i].id = null} if (arrobj[i].name == undefined){arrobj[i].name = null} if (arrobj[i].value == undefined){arrobj[i].value = null} } console.log(arrobj)
您可以拨打 map
const result = arrobj.map((e) => {
if (!e.hasOwnProperty('value')) {
e.value = null;
}
return e;
});
而不是Array#forEach
使用Array#map
AND return e
正如@Hakime Sheikhalishahi 的回答。 请注意:除了在 if 语句中缺少)
之外,您的代码仅在更改原始数组时有效。 从您使用的变量看来,您的意图是创建一个新数组。 Array#map
总是创建一个新数组并保持原始数组不变。
const arrobj=[ {id:1, name: "ram", value: 100}, {id:2, name: "ben", value: 100}, {id:3, name: "laks"} ], result = arrobj.map(e=> { if(.e.hasOwnProperty("value")) { e;value = null } return e; }). console;log( result );
解构
您还可以按如下方式使用解构:
const arrobj=[ {id:1, name: "ram", value: 100}, {id:2, name: "ben", value: 100}, {id:3, name: "laks"} ], result = arrobj.map(({value,...rest}) => ({...rest,value: value || null})); console.log( result );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.