gpt4 book ai didi

javascript - 从数组中删除除 2 个具有特定属性的对象之外的所有对象

转载 作者:行者123 更新时间:2023-12-02 16:53:29 24 4
gpt4 key购买 nike

我想根据属性从数组中删除对象 - 但想保存其中两个

var arr = [{"name": "John", "class": "warrior"},
{"name": "Jane", "class": "mage"},
{"name": "Doug", "class": "monk"},
{"name": "Danna", "class": "warrior"}, ..]

var new_arr = arr.filter(function(el) { return el.class !== "warrior"; });

// new_arr == [{"name": "Jane", "class": "mage"},
// {"name": "Doug", "class": "monk"}, ...]

如果我想删除或保留特定数量的这些对象,我该如何执行此操作 - 例如删除除两个带有 class == "warrior"的对象之外的所有对象

最佳答案

如果您不介意删除哪些战士,则可以跳过为过滤器中的前 2 个战士返回 false。您只需要一个变量来跟踪您匹配的战士数量,并在找到一个时增加它:

因此对于 John 和 Danna,matched 将分别为 1 和 2,因此保留在数组中:

var arr = [
{ "name": "John", "class": "warrior" },
{ "name": "Jane", "class": "mage" },
{ "name": "Doug", "class": "monk" },
{ "name": "Danna", "class": "warrior"},
{ "name": "Bob", "class": "warrior" },
{ "name": "Someone", "class": "mage" },
{ "name": "Bob2", "class": "warrior" },
{ "name": "Bob3", "class": "warrior" },
{ "name": "Bob4", "class": "warrior" }
];

var matched = 0;
var new_arr = arr.filter(function (el) {
return (el.class !== "warrior" || ++matched <= 2);
});

关于javascript - 从数组中删除除 2 个具有特定属性的对象之外的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385869/

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