gpt4 book ai didi

javascript - 循环遍历集合,根据操作属性将每个项目推送到新集合

转载 作者:行者123 更新时间:2023-12-03 10:11:10 26 4
gpt4 key购买 nike

例如我有这个集合:

var items = [
{accntNumber: 12345, action: "Non Derogatory", bureau: "TU", username: "pbutler"},
{accntNumber: 785, action: "Deleted", bureau: "EXP", username: "areston"},
{accntNumber: 956, action: "Deleted", bureau: "TU", username: "nikkim"},
{accntNumber: 1235, action: " 100% Non Derogatory", bureau: "TU", username: "ajaquez"},
{accntNumber: 45336, action: "Non Derogatory", bureau: "TU", username: "nikkim"},
{accntNumber: 845, action: "Newly Negative", bureau: "TU", username: "areston"},
{accntNumber: 9875, action: "No Longer On Report", bureau: "TU", username: "ajaquez"}
]

我想循环遍历它并找到“action”键并将整个对象推送到相应的数组:因此,例如,已删除的项目应放入已删除的数组中,非 Derogatory 项目应全部放入 nonDerogatoryItems 数组中。

var nonDerogatoryItems = [];
var deleted = [];
var _100nonDerogatoryItems = [];
var newlyNegative = [];
var noLongerOnReport = [];

最佳答案

如果您希望使用任何库,有一种非常简单的方法可以仅使用纯 JavaScript 来完成您想要的操作:

// Assuming you already declared 'items' with it's objects
var nonDerogatoryItems = deleted = _100nonDerogatoryItems = newlyNegative = noLongerOnReport = undefinedActionArray = [];

for(var i in items){
switch(items[i].action){
case 'Deleted':
deleted.push(items[i]);
break;
case 'Newly Negative':
newlyNegative.push(items[i]);
break;

// [...] and so on for the other possible actions

// In case any action goes missing (doesn't match the switch), you can debug this and check
// what happened, if there was any mistype or so
default:
undefinedActionArray.push(items[i]);
break;
}
}
<小时/>

现在,如果您正在考虑使用更少的行但稍微复杂一点,那么您可以这样做:

var actions = [];
for(var i in items){

// If this action wasn't set yet
if(typeof actions[items[i].action] === 'undefined')
actions[items[i].action] = []; // Starts as an empty array

// Now pushes the current item into it's group
actions[items[i].action].push(items[i]);

}

这最终会导致这样的结果:

actions = [
"Deleted" = [
{accntNumber: 785, action: "Deleted", bureau: "EXP", username: "areston"},
{accntNumber: 956, action: "Deleted", bureau: "TU", username: "nikkim"}
],
"Non Derogatory" = [
{accntNumber: 12345, action: "Non Derogatory", bureau: "TU", username: "pbutler"},
{accntNumber: 45336, action: "Non Derogatory", bureau: "TU", username: "nikkim"}
],
// [...] And so forth
]

底线

第一个示例更简单,但您将拥有一个很大的脚本,具体取决于存在的操作数量。此外,每当出现新的操作类型时,您都需要更新代码。

第二个示例更加动态并适应变化。只需几行代码,您就可以计算出 items 对象中可能存在的所有可能的action

关于javascript - 循环遍历集合,根据操作属性将每个项目推送到新集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30107427/

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