如何使用lodash基于对象文字内的另一个值更新对象的值

时间:2017-11-23 13:04:37

标签: javascript lodash

目前我有一个选择选项下拉字段。当用户从下拉列表中选择选项选项时,将返回索引值。根据索引值,我想将"Selected"值从false更改为true

var users = [
  {
    "name": "John",
    "selected": false,
    "columns": [
      {
        "index": 0,
        ...
      }
    ]
  },
  {
    "name": "Sam",
    "selected": false,
    "columns": [
      {
        "index": 1,
        ...
      }
    ]
  }
]

因此,如果具有索引值0的用户选择了第一个选项,请说明。这应该将第一个对象文字"Selected"值更新为true

var users = [
  {
    "name": "John",
    "selected": true,
    "columns": [
      {
        "index": 0,
        ...
      }
    ]
  },
  {
    "name": "Sam",
    "selected": false,
    "columns": [
      {
        "index": 1,
        ...
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:2)

您可以捕获下拉列表的selectedIndex并迭代users

检查此示例

var selectElem = document.getElementById('select');
selectElem.addEventListener('change', function() {
  var index = selectElem.selectedIndex;
  users = users.map( function(user){
     user.selected = user.columns[0].index == index; //this will set the rest of the selected values to false and only selected index to true
     return user;
  }) 
})

<强>演示

var users = [
  {
    "name": "John",
    "selected": true,
    "columns": [{ "index": 0 }]
  },
  {
    "name": "Sam",
    "selected": false,
    "columns": [{ "index": 1 }]
  }
];
var selectElem = document.getElementById('select');
selectElem.addEventListener('change', function() {
    var index = selectElem.selectedIndex;
    users = users.map( function(user){
       user.selected = user.columns[0].index == index; 
       return user;
    }); 
    console.log( "updated users ", users );
})
<select id="select">
   <option>John</option>
   <option>Sam</option>
</select>