使用linq.js从对象数组中删除元素 [英] Removing element from object array with linq.js

查看:138
本文介绍了使用linq.js从对象数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have started using linq.js a while ago, and found it very useful, but there's an issue I really can't solve somehow. I'm using angular, and I have a simple json array with the following structure:

[
  { 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元素),这些示例并没有太多帮助我.

I'm looking for the best (or at least a working) example wich could help me understanding how to remove an element of this array by the id property. I have found some examples with simple array (but not with json elements), those haven't helped me too much.

我具有以下功能来执行删除部分:

I have the following function to do the remove part:

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

推荐答案

使用 linq.js ,您需要转换数据 ToDictionary ,并使用<从 enumerable 中选择code> Single ,然后删除该项目.

With linq.js, you need do convert the data ToDictionary, get the wanted item with Single from enumerable and remove the item.

然后,您必须通过可枚举的字典再次从数组中重建数组,然后选择数组.

Then you have to rebuild the array again from dictionary via enumerable and select to array.

等等!

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>

这篇关于使用linq.js从对象数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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