javascript在对象数组中设置所有值 [英] javascript set all values in array of object

查看:434
本文介绍了javascript在对象数组中设置所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于类似问题的两部分问题.我有2个不同的数组,

Two part question about similar problems. I've got 2 different arrays,

数组1:

 array1 = [{
     name : "users",
     checked : true
   }, {
     name : "active users",
     checked : false
   }, {
     name : "completions",
     checked : false
   }]

我想知道是否有一种简单的方法可以一次将所有检查值设置为true.我知道这可以通过for循环实现:

I would like to know if there is an easy way to set all the checked values to true at once. I know this is possible with a for loop:

  for (var i = 0 ; i < array.length ; i++) {
    array[i].checked = false
  }

即使这不是很多代码,但我只是好奇是否有一种方法可以在不迭代数组中的每个对象的情况下进行操作. (不知道这是否有可能或是否有任何区别,因此,如果我对此有误,请纠正我).

Even though this is not a lot of code i'm just curious if there is a way to do this without iterating over every object in the array. (not sure if this is even possible or whether this makes any difference whatsoever, so if please correct me if i am wrong about any of this).

数组2:

array2 = [{
     value1 : false,
     value2 : true,
     value3 : false,
     value4 : false, 
     value5 : false,   
   }]

是否可以一次将所有值简单地设置为true或false(再次可以使用for循环,但宁愿不使用它)

Is it possible to simply set all the values to true or false at once (again i can use a for loop, but would prefer not to)

(我正在使用angular和lodash,但无法找到"lodash"或"angular"解决方案,但任何解决方案都可以)

(i'm using angular and lodash, but haven't been able to find a 'lodash' or 'angular' solution, but any solution will do)

推荐答案

您不能在不遍历元素的情况下执行此操作,但是可以使用功能抽象来代替for:

You can't do this without looping over the elements, however there are functional abstractions you can use instead of for:

对于数组1,您可以使用地图

For array 1, you can use map

array1.map(function(x) { 
  x.checked = true; 
  return x
});

或使用lodash中的 _.map :

Or using _.map from lodash:

_.map(array1, function(x) { 
  x.checked = true; 
  return x
});

对于数组2,您可以使用lodash中的 _.mapValues .

For array 2 you can use _.mapValues from lodash.

_.mapValues(array2[0], function() {
  return true;
});

您可以在 https://github.com/lodash/lodash/blob/a1b15df6489f47498edda244552c9804e046a45d/lodash.js#L3125

这篇关于javascript在对象数组中设置所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆