0

I've the following array and I want to delete just the entry where the name is empty like the first and the third object,how should I do it efficentlly?

var myopj =[
 { "Name": "", "Value": "" }
 { "Name": "aaa", "Value": "bbb" }, 
 { "Name": "", "Value": "" }
];

I saw some example in SO like but in my case it's little bit more complicated, I need to delete name where the value is ""

arr.splice( arr.indexOf( "name" ), 1 );
Salman Arshad
274k85 gold badges450 silver badges540 bronze badges
asked Nov 13, 2014 at 13:46

2 Answers 2

2

This should work:

myopj = myopj.filter(function(o){return o.Name});

Struictly speaking this creates a new array and assigns it to your myopj variable, rather than deleting items from the old one, but is probably the simplest way to achieve what you need.

If your array is very large and you really do want to delete items you will need to use a for loop and use splice to chop out the ones you don't need, but I think using filter is nicer.

answered Nov 13, 2014 at 13:48
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but I need the opposite ,just to keep in the array values where name is not empty ,i.e. just the third entry...
1

Use jQuery.grep() to filter the array using some criteria:

var myopj = [
 { "Name": "", "Value": "" },
 { "Name": "aaa", "Value": "bbb" },
 { "Name": "", "Value": "" }
];
var myopj_copy = $.grep(myopj, function(item, index) {
 return item.Name !== "";
});
// myopj_copy is [{"Name":"aaa","Value":"bbb"}]

This function returns a copy of array, original array remains unchanged.

answered Nov 13, 2014 at 13:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.