0

I am using Underscore.js library in my application. I have an Object

{a:"1", b:"2", c: "3", d:"no", e: "no"}

I want to condense this object to have only the properties not having "no" attribute which should result in the below object

    {a:"1", b:"2", c: "3"}

In Uderscore.js, I used the below code

_.omit(obj, 'attr');

But in the above code, instead of the 'attr', I need to have a function which will output the keys containing no values. Is there a better way to do this. Please let me know how to get the keys having 'no' values.

3
  • What is the expected output / result? Commented Dec 7, 2015 at 13:26
  • the expected output is ` {a:"1", b:"2", c: "3"}`. The object with no "no" values. Commented Dec 7, 2015 at 13:27
  • Then use omit with a predicate function: _.omit(obj, function(val) { return val === 'no'}) Commented Dec 7, 2015 at 13:30

2 Answers 2

2

You can use the _.omit as

var obj = {a:"1", b:"2", c: "3", d:"no", e: "no"};
// _.omit returns a copy of the object
obj = _.omit(obj, function(value, key, object) {
  return (value == "no");
});
console.log(obj);
Sign up to request clarification or add additional context in comments.

Comments

1

Underscore's _.omit() also accepts a 'predicate', which is their terminology for a function similar to _.filter()'s:

var o = {a:"1", b:"2", c: "3", d:"no", e: "no"}
console.log(_.omit(o, function(v){
  return v === 'no';
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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.