Home > Blockchain >  How to add property to array of objects if not found in javascript
How to add property to array of objects if not found in javascript

Time:04-19

I would like to know if property not found just add to array of object in javascript

In arrobj, one specific object has no value property, so need to add using 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}
]

I tried

const result = arrobj.forEach(e=>{
  if(!e.hasOwnProperty("value"){
   e.value=null
  }

});

CodePudding user response:

You can use the map

  const result = arrobj.map((e) => {
  if (!e.hasOwnProperty('value')) {
    e.value = null;
  }
   return e;
  });

CodePudding user response:

There is only a single typo in the approach you used. You missed to close a ) in the if statement. The following works:

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)

Here's an Approach using a for loop.

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)

  • Related