gpt4 book ai didi

javascript - 使用 linq.js 从对象数组中删除元素

转载 作者:行者123 更新时间:2023-11-30 11:51:17 25 4
gpt4 key购买 nike

我已经开始使用 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
}

最佳答案

linq.js ,您需要转换数据 ToDictionary , 用 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>

关于javascript - 使用 linq.js 从对象数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com