2

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~

8
  • 1
    You're asking how to delete a property of an object? Commented Jun 22, 2016 at 23:57
  • no delete the whole object if the value of a prop is null Commented Jun 22, 2016 at 23:59
  • Pretty sure you can do delete obj.single in this case. if you wanted to loop, maybe loop var prop in obj and if (obj[prop].id === null), you delete obj[prop] Commented Jun 23, 2016 at 0:00
  • But the object you want to delete is on a property of another object, right? Commented Jun 23, 2016 at 0:00
  • 1
    Do you want to delete obj or delete single? Commented Jun 23, 2016 at 0:00

3 Answers 3

2

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];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can use the delete operator.

e.g.

for (var prop in obj) { 
    var item = obj[prop];  
    if (!item.id) {
        delete item; 
    }
}

2 Comments

how about for deleting multiple object in one func? I'd need to remove the single and after object coz both of them have prop with null values
just loop through each item in the object
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.