Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove the dictionary element from an array by its name value

I have a list of Array for Name list & url
Want to remove from

    func getNameListData() -> [[String: Any]] {
        return [
            [
                "name”: “Jonny”,
                "imageName”: “url.png"
            ],
            [
                "name”: ”Mark”,
                "imageName”: “url.png”
            ],
            [
                "name": “Kiran”,
                "imageName": “url.png”
            ],
            [
                "name": “David”,
                "imageName": “url.png”
            ],
        ]
}

// Get Name List Array

  var nameList = self.getNameListData()

// remove Object at index Value
nameList.remove(at: 0)
// Remove element for specified element

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to remove element by name value ?

This is what I tried, its not working for me.

if let index = nameList.firstIndex(where: {$0 as? String == "Kiran" }) {
    nameList.remove(at: index)
    }

if there any way for removing an element from array of JSONDictionary i.e [[String:Any]]

It give following warning

Cast from ‘JSONDictionary’ (aka ‘Dictionary<String, Any>’) to unrelated type ‘String’ always fails
Cast from ‘JSONDictionary’ (aka ‘Dictionary<String, Any>’) to unrelated type ‘String’ always fails

Result count = 3.

>Solution :

Very close — right now, you’re trying to caste the entire [String:Any] dictionary to String. Instead, you should be looking at just the "name" entry and casting it’s value to String to compare to "Kiran".

if let index = nameList.firstIndex(where: {$0["name"] as? String  == "Kiran" }) {
    nameList.remove(at: index)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading