удалить ключ совпадающего номера в [String: [NSNumber]] - PullRequest
0 голосов
/ 27 июня 2019

Как удалить значение из словаря с массивом значений. У меня есть ответ от сервера, как показано ниже:

[  
   "business_proof":[  
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      -1,// business_proof contains -1, I want to remove this key like wise any other contains
      0,
      0
   ],
   "reference_proof":[  
      1,
      2,
      1
   ],
   "vehicle_proof":[  
      1,
      1,
      2
   ],
   "previous_loan_track":[  
      2,
      2,
      0,
      0,
      2,
      2
   ],
   "banking_proof":[  
      1,
      1
   ],
   "income_proof":[  
      0,
      0,
      2,
      0,
      2,
      1,
      2,
      0,
      0
   ],
   "signature_proof":[  
      2,
      2,
      1,
      2,
      2,
      2
   ],
   "employment_proof":[  
      2,
      1,
      2,
      2,
      2,
      2,
      2
   ],
   "guarantor_proof":[  
      1,
      2,
      2
   ],
   "pdc_proof":[  
      1,
      0
   ],
   "address_proof":[  
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      3
   ],
   "age_proof":[  
      2,
      2,
      2,
      2,
      2,
      2,
      1,
      2
   ],
   "contact_proof":[  
      0,
      2,
      2
   ],
   "photo_id_proof":[  
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2,
      2
   ]
]

Второй ответ

[  
   "signature_proof":[  
      "pan_card",
      "driving_licence",
      "accepted_documents",
      "passport",
      "cancelled_cheque",
      "bank_report"
   ],
   "guarantor_proof":[  
      "accepted_documents",
      "co_applicant",
      "guarantor"
   ],
   "previous_loan_track":[  
      "housing_loan",
      "vehicle_loan",
      "over_draft_limit",
      "accepted_documents",
      "business_loan",
      "personal_loan"
   ],
   "address_proof":[  
      "bank_statement",
      "voter_id",
      "rental_agreement",
      "eb_bill",
      "registration_document",
      "hr_letter",
      "driving_licence",
      "property_tax_receipt",
      "telephone_bill",
      "cc_statement",
      "gas_bill",
      "aadhaar_card",
      "passport",
      "ration_card",
      "accepted_documents"
   ],
   "vehicle_proof":[  
      "vehi_insurance",
      "vehi_rc",
      "accepted_documents"
   ],
   "business_proof":[  
      "business_commencement_certificate",
      "ssi_msme_certificate",
      "business_transactions",
      "mou",
      "aoa",
      "gst_no",
      "tan_no",
      "business_agreements",
      "accepted_documents",
      "shop_and_establishment_certificate",
      "incorporation_certificate"
   ],
   "banking_proof":[  
      "bank_statement",
      "accepted_documents"
   ],
   "income_proof":[  
      "form_16",
      "profit_loss_statement",
      "rental_income_proof",
      "payslip",
      "income_in_cash_proof",
      "accepted_documents",
      "brokerage_income_proof",
      "it_returns",
      "audited_balance_sheet"
   ],
   "reference_proof":[  
      "ref2",
      "accepted_documents",
      "ref1"
   ],
   "employment_proof":[  
      "employee_id_card",
      "accepted_documents",
      "payslip",
      "relieving_letter",
      "comp_app_letter",
      "hr_letter",
      "epf_no_uan_no"
   ],
   "age_proof":[  
      "employee_id_card",
      "ration_card",
      "pan_card",
      "passport",
      "voter_id",
      "school_certificate",
      "accepted_documents",
      "aadhaar_card"
   ],
   "contact_proof":[  
      "accepted_documents",
      "landline_bill",
      "mobile_bill"
   ],
   "photo_id_proof":[  
      "employee_id_card",
      "nrega_card",
      "ration_card",
      "bank_passbook",
      "pan_card",
      "passport",
      "voter_id",
      "driving_licence",
      "accepted_documents",
      "aadhaar_card"
   ],
   "pdc_proof":[  
      "cheque_book",
      "accepted_documents"
   ]
]

Оба являются массивом словаря, оба будут иметь один и тот же ключ. Я знаю, что эта структура совершенно неверна.

business_proof содержит только - 1, поэтому я хочу удалить оба места.

Здесь мне нужно удалить ключ и значения, если кто-либо из ключей содержит -1.

Я пытаюсь так, но это показывает ошибку компилятора

finalValueArray.removeAll(where: { $0.contains(-1) })

Ответы [ 5 ]

1 голос
/ 27 июня 2019

Перечислите индексный словарь, найдите вхождения -1 и отфильтруйте indices. Затем поменяйте местами найденные индексы и удалите элементы из обоих массивов. Код считает, что оба словаря являются типами значений

var indexDict = ["business_proof":[0,0,0,0,0,0,0,0,-1,0,0] ...
var valueDict = ["signature_proof":["pan_card","driving_licence","accepted_documents","passport","cancelled_cheque","bank_report"] ...


for (key, value) in indexDict {
    let foundIndices = value.indices.filter({value[$0] == -1})
    for index in foundIndices.reversed() {
        indexDict[key]!.remove(at: index)
        valueDict[key]!.remove(at: index)
    }

}
1 голос
/ 27 июня 2019

Вы можете отфильтровать словарь, чтобы удалить записи, содержащие -1 в их значении.

let filteredArrayOnDict = dataDict.filter {  value.contains{ $0 != -1 } }

FilterArrayOnDict - это массив кортежей. Теперь, если вы хотите создать словарь из него. Вы можете сделать это так:

let filteredDictionary = filteredArrayOnDict.reduce(into: [:]) { $0[$1.0] = $1.1}

Теперь у вас есть только записи в FilterDictionary, которые не имеют -1 в своем значении.

1 голос
/ 27 июня 2019

Вы можете просто использовать комбинацию forEach и contains на dictionary, например,

var dictionary = ["business_proof": [0, 0, 1, -1, 2, -1], "reference_proof": [1, 2, 1], "vehicle_proof": [-1, 0, 0, 2]]

dictionary.forEach { (key,value) in
    dictionary[key] = value.contains(-1) ? nil : value
}

print(dictionary) //["reference_proof": [1, 2, 1]]

Или вы можете просто применить filter на dictionary как,

dictionary = dictionary.filter({ !$0.value.contains(-1) })

print(dictionary) //["reference_proof": [1, 2, 1]]
1 голос
/ 27 июня 2019

Вы можете использовать цикл while для удаления всех пар key-value, которые содержат -1 из обоих словарей.

var dict1 = ["business_proof":[0,0,0,0,0,0,0,0,-1,0,0],"reference_proof":[1,2,1],"vehicle_proof":[1,1,2],"previous_loan_track":[2,2,0,0,2,2],"banking_proof":[1,1],"income_proof":[0,0,2,0,2,1,2,0,0],"signature_proof":[2,2,1,2,2,2],"employment_proof":[2,1,2,2,2,2,2],"guarantor_proof":[1,2,2],"pdc_proof":[1,0],"address_proof":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,3],"age_proof":[2,2,2,2,2,2,1,2],"contact_proof":[0,2,2],"photo_id_proof":[2,2,2,2,2,2,2,2,2,2]]
var dict2 = ["signature_proof":["pan_card","driving_licence","accepted_documents","passport","cancelled_cheque","bank_report"],"guarantor_proof":["accepted_documents","co_applicant","guarantor"],"previous_loan_track":["housing_loan","vehicle_loan","over_draft_limit","accepted_documents","business_loan","personal_loan"],"address_proof":["bank_statement","voter_id","rental_agreement","eb_bill","registration_document","hr_letter","driving_licence","property_tax_receipt","telephone_bill","cc_statement","gas_bill","aadhaar_card","passport","ration_card","accepted_documents"],"vehicle_proof":["vehi_insurance","vehi_rc","accepted_documents"],"business_proof":["business_commencement_certificate","ssi_msme_certificate","business_transactions","mou","aoa","gst_no","tan_no","business_agreements","accepted_documents","shop_and_establishment_certificate","incorporation_certificate"],"banking_proof":["bank_statement","accepted_documents"],"income_proof":["form_16","profit_loss_statement","rental_income_proof","payslip","income_in_cash_proof","accepted_documents","brokerage_income_proof","it_returns","audited_balance_sheet"],"reference_proof":["ref2","accepted_documents","ref1"],"employment_proof":["employee_id_card","accepted_documents","payslip","relieving_letter","comp_app_letter","hr_letter","epf_no_uan_no"],"age_proof":["employee_id_card","ration_card","pan_card","passport","voter_id","school_certificate","accepted_documents","aadhaar_card"],"contact_proof":["accepted_documents","landline_bill","mobile_bill"],"photo_id_proof":["employee_id_card","nrega_card","ration_card","bank_passbook","pan_card","passport","voter_id","driving_licence","accepted_documents","aadhaar_card"],"pdc_proof":["cheque_book","accepted_documents"]]

while let invalid = dict1.first(where: { $0.value.contains(-1) }) {
    dict1.removeValue(forKey: invalid.key)
    dict2.removeValue(forKey: invalid.key)
}
print(dict1)//["reference_proof":[1,2,1],"vehicle_proof":[1,1,2],"previous_loan_track":[2,2,0,0,2,2],"banking_proof":[1,1],"income_proof":[0,0,2,0,2,1,2,0,0],"signature_proof":[2,2,1,2,2,2],"employment_proof":[2,1,2,2,2,2,2],"guarantor_proof":[1,2,2],"pdc_proof":[1,0],"address_proof":[2,2,2,2,2,2,2,2,2,2,2,2,2,2,3],"age_proof":[2,2,2,2,2,2,1,2],"contact_proof":[0,2,2],"photo_id_proof":[2,2,2,2,2,2,2,2,2,2]]
print(dict2)//["signature_proof":["pan_card","driving_licence","accepted_documents","passport","cancelled_cheque","bank_report"],"guarantor_proof":["accepted_documents","co_applicant","guarantor"],"previous_loan_track":["housing_loan","vehicle_loan","over_draft_limit","accepted_documents","business_loan","personal_loan"],"address_proof":["bank_statement","voter_id","rental_agreement","eb_bill","registration_document","hr_letter","driving_licence","property_tax_receipt","telephone_bill","cc_statement","gas_bill","aadhaar_card","passport","ration_card","accepted_documents"],"vehicle_proof":["vehi_insurance","vehi_rc","accepted_documents"],"banking_proof":["bank_statement","accepted_documents"],"income_proof":["form_16","profit_loss_statement","rental_income_proof","payslip","income_in_cash_proof","accepted_documents","brokerage_income_proof","it_returns","audited_balance_sheet"],"reference_proof":["ref2","accepted_documents","ref1"],"employment_proof":["employee_id_card","accepted_documents","payslip","relieving_letter","comp_app_letter","hr_letter","epf_no_uan_no"],"age_proof":["employee_id_card","ration_card","pan_card","passport","voter_id","school_certificate","accepted_documents","aadhaar_card"],"contact_proof":["accepted_documents","landline_bill","mobile_bill"],"photo_id_proof":["employee_id_card","nrega_card","ration_card","bank_passbook","pan_card","passport","voter_id","driving_licence","accepted_documents","aadhaar_card"],"pdc_proof":["cheque_book","accepted_documents"]]


Создать struct и инициализировать структуруобъекты с обоими значениями словаря.Затем сохраните объекты структуры в массиве.Теперь вы можете фильтровать массив по его значениям

struct Proof {
    var title: String
    var arr: [Int]
    var documents: [String]
}
var proofs = [Proof]()
dict1.forEach {
    if let docs = dict2[$0.key] {
        proofs.append(Proof(title: $0.key, arr: $0.value, documents: docs))
    }
}
print(proofs)
let validProofs = proofs.filter { !$0.arr.contains(-1) }
print(validProofs)
1 голос
/ 27 июня 2019

Вы можете использовать filter, насколько я понимаю,

var filteredItems = object.filter { !$0.value.contains(-1)}

Вы можете получить все элементы, которые содержат -1

var minusOneItems = object.filter { $0.value.contains(-1)}

и чем

for negativeItem in minusOneItems {
    object.removeValue(forKey: negativeItem.key)
}

Это зависит от того, что вам нужно.

...