1

Using Underscorejs, would anyone know how to simply replace one attribute of an object?

For example, if I have this:

var obj = {
 "id" : 123,
 "date" : 142002020,
 "name" : "somename",
 "active" : 1
}

Now I want to set active to 0;

I could use _.collect and check for 'active' then update it and return to a new variable, but it seems like there's a better way, I'm just not seeing it.

Thanks!

1
  • Did you ever find the solution to this? Commented Apr 7, 2016 at 13:10

1 Answer 1

5

Why don't you just obj['active'] = 0, you don't need underscore for changing an property.

EDIT

If you need to find a nested key maybe you could use a recursive function.

var obj = {
   'foo' : {
      'bar' : {
         'active' : 1
      }
   }
}

function replaceKey (obj, key, value) {
   var _obj = _(obj)

    _obj.each(function (v, k) {
      if (k === key) {
         obj[k] = value
      } else if (obj[k] === Object(obj[k])) {
         replaceKey(obj[k], key, value)
      }
   })

   return _obj;
}

console.log('should be active:', obj.foo.bar.active === 1)
replaceKey(obj, 'active', 0)
console.log('should not be active:', obj.foo.bar.active === 0)
Sign up to request clarification or add additional context in comments.

2 Comments

Probably because they want to chain that with other calls.
Sorry, yeah my example is bad. Yes that would be fine, but sometimes its nested deeper and I don't know how deep, like, ideally it would "find" a key, no matter how deep it is and change it's value.

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.