javascript - Underscore js replace item in object - Stack Overflow

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

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!

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!

Share Improve this question asked May 10, 2012 at 20:01 dzmdzm 23.6k51 gold badges152 silver badges229 bronze badges 1
  • Did you ever find the solution to this? – nikjohn Commented Apr 7, 2016 at 13:10
Add a ment  | 

1 Answer 1

Reset to default 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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745326392a4622675.html

相关推荐

  • javascript - Underscore js replace item in object - Stack Overflow

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

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信