'How to add property to array of objects if not found in javascript
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
}
});
Solution 1:[1]
You can use the map
const result = arrobj.map((e) => {
if (!e.hasOwnProperty('value')) {
e.value = null;
}
return e;
});
Solution 2:[2]
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)
Solution 3:[3]
Instead of Array#forEach use Array#map AND return e as in @Hakime Sheikhalishahi's answer.
Please note: Other than a missing ) in the if statement your code works only that it changes the original array. From the variables you've used it appears that your intention is to create a new array. Array#map always creates a new array and leaves the original one intact.
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 );
Destructuring
You can also use destructuring as follows:
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 );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hakime Sheikhalishahi |
| Solution 2 | VLAZ |
| Solution 3 |
