更改对象数组中的布尔值

时间:2019-05-23 08:56:40

标签: javascript

我有单选按钮,我需要将选定的单选按钮更改为true,将其他更改为false

changeHandler (index, event) {
    this.array[index].checked = true;
}

我具有以下数组结构:

[
 {checked: false, title: 'first'},
 {checked: false, title: 'second'},
 {checked: false, title: 'third'}
]

当我选择收音机“ first”时,我需要将此obj值更改为true,将其他obj值更改为false,依此类推。

3 个答案:

答案 0 :(得分:0)

您可以将所有checked个成员设置为false,但将其成员具有选定的索引:

changeHandler (index, event) {
    this.array.forEach((elem, idx) => elem.checked = idx == index);
}

答案 1 :(得分:0)

您可以按标题找到所有输入,并添加一个事件侦听器。

这是我的实现方式

// after document load

const myRadioButtons = [
 {checked: false, title: 'first'},
 {checked: false, title: 'second'},
 {checked: false, title: 'third'}
];

myRadioButtons.forEach(radio => {
  function updateRadioValue(id, value) {
    document.querySelector(`#${id}`).checked = value;
    myRadioButtons.find(item => item.title === id).checked = value;
  }
  
  function checkRadioAndResetOthers() {
    myRadioButtons
      .filter(item => item.title !== radio.title)
      .forEach(item => updateRadioValue(item.title, false));
  
    radio.checked = true;
    console.log(myRadioButtons);
  }

  document
    .querySelector(`#${radio.title}`)
    .addEventListener('change', checkRadioAndResetOthers);
})
<input type="radio" id="first"/> First
<input type="radio" id="second"/> Second
<input type="radio" id="third"/> Third

答案 2 :(得分:0)

请参见Array.prototype.forEach

const array = [
 {checked: false, title: 'first'},
 {checked: false, title: 'second'},
 {checked: false, title: 'third'}
];

function changeHandler(index) {
  array.forEach((item, i) => item.checked = index === i);
}

changeHandler(0)
console.log(array);

changeHandler(1)
console.log(array);

changeHandler(2)
console.log(array);