【问题标题】:Removing element from object array with linq.js使用 linq.js 从对象数组中删除元素
【发布时间】:2016-09-08 08:20:43
【问题描述】:

我不久前开始使用linq.js,发现它非常有用,但有一个问题我真的无法解决。我正在使用 angular,并且我有一个简单的 json 数组,其结构如下:

[
  { id: 1, name: 'John', age: 20},
  { id: 2, name: 'Josh', age: 34},
  { id: 3, name: 'Peter', age: 32},
  { id: 4, name: 'Anthony', age: 27},
]

我正在寻找最好的(或至少是一个有效的)示例,它可以帮助我理解如何通过id 属性删除该数组的元素。我找到了一些简单数组的例子(但不是 json 元素),这些对我帮助不大。

我有以下功能来做删除部分:

this.removePerson = function(id) {
   //here's how I access the array
   vm.people
}

【问题讨论】:

    标签: javascript angularjs linq.js


    【解决方案1】:

    使用linq.js,您需要转换数据ToDictionary,从enumerable 获取带有Single 的想要的项目并删除该项目。

    然后你必须通过 enumerable 再次从字典中重建数组并选择到数组。

    等等!

    var data = [{ id: 1, name: 'John', age: 20}, { id: 2, name: 'Josh', age: 34}, { id: 3, name: 'Peter', age: 32}, { id: 4, name: 'Anthony', age: 27}],
        enumerable = Enumerable.From(data),
        dictionary = enumerable.ToDictionary();
    
    dictionary.Remove(enumerable.Single(s => s.id === 3));
    console.log(dictionary.ToEnumerable().Select(s => s.Key).ToArray());
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

    【讨论】:

      【解决方案2】:
         //assuming your sample data
          var vm = {};
          vm.people = [
            { id: 1, name: 'John', age: 20},
            { id: 2, name: 'Josh', age: 34},
            { id: 3, name: 'Peter', age: 32},
            { id: 4, name: 'Anthony', age: 27},
          ];
      
          //just loop through and delete the matching object
          this.removePerson = function(id) {
            for(var i=0;i<vm.people.length;i++){
                if(vm.people[i].id == id){
                vm.people.splice(i, 1);//removes one item from the given index i
                break;
                }
            }
          };
      

      JSBin here

      【讨论】:

      • 感谢您的解决方案,非常有用:) 但是,如果可能的话,我想用 linq.js 解决问题,但如果没有人尽快回复,我会接受您的回答即使以另一种方式解决了我的问题。
      • 没关系,在他们的方法中,他们会做一些类似于我上面编码的事情。对于复杂的功能/或依赖于浏览器的代码,我们应该坚持使用库。我不虽然看不到这个问题。
      • 嗯,你可能是对的,因为使用库的这一小段代码是不必要的
      猜你喜欢
      • 2020-01-31
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 2018-03-29
      相关资源
      最近更新 更多