How to delete object in array of dictionaries using Key Value
You can get the index of the dictionary that you want to delete using .index(where:)
method which performs performs 0(n):
let index = array.index(where: { dictionary in
guard let value = dictionary["photo_id"] as? Int
else { return false }
return value == 255024731588044
})
You can delete it using the index
value if it is not nil
:
if let index = index {
array.remove(at: index)
}
Here you can download the playground.
How to remove the dictionary element from an array by its name value
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)
}
Remove value from Array of Dictionaries
If I understood you questions correctly, this should work
var posts: [[String:String]] = [
["a": "1", "b": "2"],
["x": "3", "y": "4"],
["a": "5", "y": "6"]
]
for (index, var post) in posts.enumerate() {
post.removeValueForKey("a")
posts[index] = post
}
/*
This will posts = [
["b": "2"],
["y": "4", "x": "3"],
["y": "6"]
]
*/
Since both your dictionary and the wrapping array are value types just modifying the post
inside of the loop would modify a copy of dictionary (we created it by declaring it using var
), so to conclude we need to set the value at index
to the newly modified version of the dictionary
How to remove array from values in a dictionary
In order to produce the required output you will need a list (set) of keys that should not be modified. Something like this:
dict_ = {
"contact_uuid": ["67460e74-02e3-11e8-b443-00163e990bdb"],
"choices": ["None"],
"value": [""],
"cardType": [""],
"step": ["None"],
"optionId": ["None"],
"path": [""],
"title": [""],
"description": [""],
"message": [""]
}
for k, v in dict_.items():
if isinstance(v, list) and k not in {'value', 'cardType', 'step', 'optionId', 'path'}:
dict_[k] = v[0]
print(dict_)
Output:
{'contact_uuid': '67460e74-02e3-11e8-b443-00163e990bdb', 'choices': 'None', 'value': [''], 'cardType': [''], 'step': ['None'], 'optionId': ['None'], 'path': [''], 'title': '', 'description': '', 'message': ''}
how do I remove one single element from an array dictionary?
You can use indexOf as follow:
var dict = ["H": ["hello", "hi"], "J": ["joker"]]
if let index = dict["H"]?.indexOf("hi") {
dict["H"]?.removeAtIndex(index)
}
dict // ["H": ["hello"], "J": ["joker"]]
Xcode 8 beta • Swift 3 would be:
var dict = ["H": ["hello", "hi"], "J": ["joker"]]
if let index = dict["H"]?.index(of: "hi") {
dict["H"]?.remove(at: index)
}
dict
Remove item that is inside of an array which is the value in a dictionary Swift 2
Many answers that cover the mutation of dictionary entries tend to focus on the remove value -> mutate value -> replace value idiom, but note that removal is not a necessity. You can likewise perform an in-place mutation using e.g. optional chaining
dict["Furniture"]?.removeAtIndex(1)
print(dict)
/* ["Furniture": ["Table", "Bed"],
"Food": ["Pancakes"]] */
Note however that using the .removeAtIndex(...)
solution is not entirely safe, unless you perform an array bounds check, making sure that the index for which we attempt to remove an element actually exists.
As a safe in-place-mutation alternative, use the where
clause of an optional binding statement to check the the index we want to remove is not out of bounds
let removeElementAtIndex = 1
if let idxs = dict["Furniture"]?.indices where removeElementAtIndex < idxs.endIndex {
dict["Furniture"]?.removeAtIndex(removeElementAtIndex)
}
Another safe alternative is making use of advancedBy(_:limit)
to get a safe index to use in removeAtIndex(...)
.
let removeElementAtIndex = 1
if let idxs = dict["Furniture"]?.indices {
dict["Furniture"]?.removeAtIndex(
idxs.startIndex.advancedBy(removeElementAtIndex, limit: idxs.endIndex))
}
Finally, if using the remove/mutate/replace idiom, another safe alternative is using a flatMap
for the mutating step, removing an element for a given index, if that index exists in the array. E.g., for a generic approach (and where
clause abuse :)
func removeSubArrayElementInDict<T: Hashable, U>(inout dict: [T:[U]], forKey: T, atIndex: Int) {
guard let value: [U] = dict[forKey] where
{ () -> Bool in dict[forKey] = value
.enumerate().flatMap{ $0 != atIndex ? $1 : nil }
return true }()
else { print("Invalid key"); return }
}
/* Example usage */
var dict = [String:[String]]()
dict = ["Furniture": ["Table", "Chair", "Bed"], "Food": ["Pancakes"]]
removeSubArrayElementInDict(&dict, forKey: "Furniture", atIndex: 1)
print(dict)
/* ["Furniture": ["Table", "Bed"],
"Food": ["Pancakes"]] */
javascript : Remove item from list of dictionary with name
You can use Array.prototype.filter()
to clean it.
let arr1 = [{name:'item0',value:0},{name:'item1',value:1},{name:'item2',value:2},{name:'item3',value:3}];
const itemsToRemove = ['item1','item2'];
arr1 = arr1.filter(obj => !itemsToRemove.includes(obj.name));
console.log(arr1);
Remove dictionary from array where value is empty string (Using Higher Order Functions)
Based on your for
loop, it seems you want to remove dictionaries from details
if any key-value pair therein contains an empty String
, ""
, as a value. For this, you could e.g. apply filter
on details
, and as a predicate to the filter
, check the values
property of each dictionary for the non-existance of ""
(/non-existance of an empty String
). E.g.
var details: [[String: String]] = [
["name": "a", "age": "1"],
["name": "b", "age": "2"],
["name": "c", "age": ""]
]
let filteredDetails = details.filter { !$0.values.contains("") }
print(filteredDetails)
/* [["name": "a", "age": "1"],
"name": "b", "age": "2"]] */
or,
let filteredDetails = details
.filter { !$0.values.contains(where: { $0.isEmpty }) }
On another note: seeing you use an array of dictionaries with a few seemingly "static" keys, I would advice you to consider using a more appropriate data structure, e.g. a custom Struct
. E.g.:
struct Detail {
let name: String
let age: String
}
var details: [Detail] = [
Detail(name: "a", age: "1"),
Detail(name: "b", age: "2"),
Detail(name: "c", age: "")
]
let filteredDetails = details.filter { !$0.name.isEmpty && !$0.age.isEmpty }
print(filteredDetails)
/* [Detail(name: "a", age: "1"),
Detail(name: "b", age: "2")] */
How do I remove objects from a JavaScript associative array?
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the delete
operator:
const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
Note that when delete
is applied to an index property of an Array
, you will create a sparsely populated array (ie. an array with a missing index).
When working with instances of Array
, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice
or Array#pop
.
Note that the delete
operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o
, then o
will subsequently be garbage collected in the normal way.
Using the delete
operator can affect JavaScript engines' ability to optimise code.
Related Topics
How Does Appdelegate.Swift Replace Appdelegate.H and Appdelegate.M in Xcode 6.3
Chain Network Calls Sequentially in Combine
Why Do Two Distinct Array Literals Equal Each Other in Swift
Guard Let Error: Initializer for Conditional Binding Must Have Optional Type Not 'String'
Swiftui How to Animate Each Character in Textfield
Cannot Call Value of Non-Function Type 'Ciimage'
Check If Color Is Blue(Ish), Red(Ish), Green(Ish),
Why Specify [Unowned Self] in Blocks Where You Depend on Self Being There
Swift Codable with Different Array Types
Rotate a Sprite to Sprite Position Not Exact in Spritekit with Swift
Generics and Functional Programming in Swift
Can Not Cast Value of Type Nstaggedpointerstring to Nsdictionary
Swift Lazy Stored Property Versus Regular Stored Property When Using Closure
Expression Pattern of Type 'String' Cannot Match Values of Type 'Nsstoryboardsegue.Identifier