I have list of objects whom I want to loop through to see for the value of a key, in this I want to remove objects whode id= "null". Below is snippet:
obj: {
after:{
id: null,
name:'test',
address: '63784hgj'
},
before:{
id: 678346,
name:'test',
address: '63784hgj'
},
single:{
id: null,
name:'test',
address: '63784hgj'
},
range:{
id: 65847,
name:'test',
address: '63784hgj'
}
}
I tried some sloppy way of doing this, considering I know the object that has id with null value:
obj.abc.id.destroy;
obj.abc3.id.destroy;
below is the way the object is seen: enter image description here
is there any way I could remove objects that dont have null values for their id's?
Thx~
3 Answers 3
If you want to just delete single:
delete obj.single;
If you want to delete multiple objects within obj:
for (var prop in obj){
if (obj[prop].id === null){
delete obj[prop];
}
}
Comments
you can use the delete operator.
e.g.
for (var prop in obj) {
var item = obj[prop];
if (!item.id) {
delete item;
}
}
I think these are simpler answers than above (with respect to line of code):
var obj= {
after:{ id: null, name:'test', address: '63784hgj' },
before:{ id: 678346, name:'test', address: '63784hgj' },
single:{ id: null, name:'test', address: '63784hgj' },
range:{ id: 65847, name:'test', address: '63784hgj' },
};
// Solution #1: set items to new object.
var newObj = {};
Object.keys(obj)
.forEach(k => obj[k].id && (newObj[k] = obj[k]));
// Solution #2: delete unwanted from object itself.
Object.keys(obj)
.forEach(k => !obj[k].id && delete obj[k]);
console.log(newObj);
console.log(obj);
delete obj.singlein this case. if you wanted to loop, maybe loopvar prop in objandif (obj[prop].id === null), youdelete obj[prop]objor deletesingle?