【问题标题】:How to toggle array values by their property value如何通过属性值切换数组值
【发布时间】:2017-07-18 10:41:10
【问题描述】:

我想知道如何通过属性名称​​切换数组中的值。

例如,拥有以下数组,我想切换(按钮)所有具有名为 a 和/或 b 等属性的值打开和关闭。

输入

const arr_input = [
  { a: 1, b: 2, c: 3  },
  { a: 3, b: 9, c: 12  }
];

输出

const arr_output = [
  { b: 2, c: 3  },
  { b: 9, c: 12  }
];

https://jsfiddle.net/cdp0a539/

【问题讨论】:

  • 你说的"toggle"是什么意思?您似乎在问,如何删除数组并将值重新添加到数组中。
  • @evolutionxbox 正确。我想删除然后添加相同的值/多个值。例如,我想切换“a”和“b”。

标签: javascript arrays ecmascript-6


【解决方案1】:

您可以使用array.reduce 过滤掉您不希望在输出中出现的属性。

我试图通过使用toggleArray 来复制下面的情况,您可以在其中传递一个您不想要的属性。它将过滤掉数组并返回所需的输出。

var arr_input = [{
    a: 1,
    b: 2,
    c: 3
  },
  {
    a: 3,
    b: 9,
    c: 12
  }
];

var toggleArray = function(propToToggle) {
  return arr_input.reduce((arr, inp) => {
    var obj = {};
    for(var key in inp) {
     if(key != propToToggle) {
       obj[key] = inp[key];
     }
    }
    arr.push(obj);
    return arr;
  }, []);
}

var arr_output = toggleArray('a');

console.log(arr_output);

arr_output = toggleArray('b');
console.log(arr_output);

arr_output = toggleArray('c');
console.log(arr_output);

【讨论】:

    【解决方案2】:

    取自您的小提琴,以下将返回原始数组的 副本,其中删除了选定的属性

    const items = [
       { 'a': 1, 'b': 2, 'c': 3  },
       { 'a': 3, 'b': 9, 'c': 12  }
    ];
    
    const toggleProperty = (value) => {
      return items.map(function(el) { 
        var o = Object.assign({},el);
        delete o[value];
        return o;
      });
    }
    <button type="button" id="a" 
            onClick="console.log(toggleProperty('a'))">Toggle a</button>
    
    <button type="button" id="b" 
            onClick="console.log(toggleProperty('b'))">Toggle b</button>
    
    <button type="button" id="c" 
            onClick="console.log(toggleProperty('c'))">Toggle c</button>

    【讨论】:

      【解决方案3】:

      为了切换(意味着当您第二次切换时将再次添加一个属性,而与任何其他属性的切换状态无关),您需要保持状态,知道当前属性是打开还是关闭。

      我会为此引入一个额外的对象,它具有所有属性,但其值是布尔值:应该包含该属性时为 true,否则为 false。

      这是一个有效的 sn-p,它将仅显示具有当前“打开”属性的对象:

      const items = [
             { 'a': 1, 'b': 2, 'c': 3  },
             { 'a': 3, 'b': 9, 'c': 12  }
          ],
          // Keep an object with same keys, but with all values set to true:
          state = Object.assign(...Object.keys(items[0]).map( key => ({ [key]: true }) ));
      
      const toggleProperty = (key) => {
          // Toggle state, so you know which keys are currently off or on:
          state[key] = !state[key]; 
          // Produce the desired object and return it
          return items.map( obj =>
              Object.assign(...Object.keys(state).map( key => 
                  state[key] ? { [key]: obj[key] } : {}
              ))
          );
      }
      
      // Handle the button clicks:
      a.onclick = b.onclick = c.onclick = function () {
          output.textContent = JSON.stringify(toggleProperty(this.id), null, 2);
          return false;
      };
      // At page load, show the complete objects (everything is toggled on):
      output.textContent = JSON.stringify(items, null, 2);
      <button id="a">Toggle a</button>
      <button id="b">Toggle b</button>
      <button id="c">Toggle c</button>
      <pre id="output"></pre>        

      【讨论】:

        【解决方案4】:

        您可以使用属性的副本并使用数组过滤键。

        const toggle = (array, keys) =>
            array.map(o =>
                Object.assign(
                    {},
                    ...Object
                    .keys(o)
                    .filter(k => !keys.includes(k))
                    .map(k => ({ [k]: o[k] }))
                )
            ),
            input = [{ a: 1, b: 2, c: 3  }, { a: 3, b: 9, c: 12  }];
        
        console.log(toggle(input, ['a', 'b', 'c']));
        console.log(toggle(input, ['a', 'b']));
        console.log(toggle(input, ['a']));

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-18
          • 2020-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-14
          • 1970-01-01
          • 2020-01-06
          相关资源
          最近更新 更多