Get element from array of dictionaries according to key
For that no need to map
the array. You can use contains(where:)
if array.contains(where: { $0["name"] as? String == value }) {
print("Exist")
}
If you want object(dictionary) from array also than you can use first(where:)
if let dict = array.first(where: { $0["name"] as? String == value }) {
print(dict)
}
For more on first(where:)
check this SO Thread
Get key value from array of dictionaries if you know another key value
var array2 = ["R1", "RT", "RG"]
var elements = [{
"COLOR": "RED",
"NAME": "R1"
}, {
"COLOR": "BLUE",
"NAME": "R2"
}]
var names = ["R1", "R2"]
for (var name in names) {
if (array2.includes(names[name])) {
const matchName = elements.find(element => element.NAME === names[name]);
console.log("NAME is " + matchName.NAME + " color for that name is " + matchName.COLOR)
}
}
Get value of a key from a dictionary array JavaScript
This should help:
const car = [{id: "1", brand: "Opel"}, {id: "2", brand: "Haima"},{id: "3", brand: "Toyota"}];
const brands = car.map(({ brand }) => brand);
Map value in particular key in array of dictionary
Using a recursive method that performs the update
func update(key:String, in dict: [String:Any], with value: Any) -> [String:Any] {
var out = [String:Any]()
if let _ = dict[key] {
out = dict
out[key] = value
} else {
dict.forEach {
if let innerDict = $0.value as? [String:Any] {
out[$0.key] = update(key: key, in: innerDict, with: value)
} else {
out[$0.key] = $0.value
}
}
}
return out
}
we can use a simple map
call
var original = [["currentObject": ["passport": 0, "pan_card": 0, "ration_card": 0], "title": "Documents list"], ["currentObject": ["pan_card": 0, "dl": 0, "voter": 0], "title": "Second Documents list"]]
let result = original.map{ update(key: "pan_card", in: $0, with: 1)}
The update
function was based on this answer
Getting a list of values from a list of dicts
Assuming every dict has a value
key, you can write (assuming your list is named l
)
[d['value'] for d in l]
If value
might be missing, you can use
[d['value'] for d in l if 'value' in d]
Search in Array of Dictionaries by key name
Use the filter
function
let foo = [
["selectedSegment":0, "severity":3, "dataDictKey": "critical"],
["selectedSegment":1, "severity":2, "dataDictKey": "major"],
["selectedSegment":2, "severity":1, "dataDictKey": "minor"],
]
let filteredArray = foo.filter{$0["severity"]! == 2}
print(filteredArray.first ?? "Item not found")
or indexOf
if let filteredArrayIndex = foo.indexOf({$0["severity"]! == 2}) {
print(foo[filteredArrayIndex])
} else {
print("Item not found")
}
or NSPredicate
let predicate = NSPredicate(format: "severity == 2")
let filteredArray = (foo as NSArray).filteredArrayUsingPredicate(predicate)
print(filteredArray.first ?? "Item not found")
Swift 3 Update:
indexOf(
has been renamed toindex(where:
filteredArrayUsingPredicate(predicate)
has been renamed tofiltered(using: predicate)
How do I access the index of items inside an array that is inside a dictionary?
I think you meant to write:
for key in mydict:
for i, x in enumerate(my_dict[key][2]):
#other code here
How do I extract all the values of a specific key from a list of dictionaries?
If you just need to iterate over the values once, use the generator expression:
generator = ( item['value'] for item in test_data )
...
for i in generator:
do_something(i)
Another (esoteric) option might be to use map
with itemgetter
- it could be slightly faster than the generator expression, or not, depending on circumstances:
from operator import itemgetter
generator = map(itemgetter('value'), test_data)
And if you absolutely need a list, a list comprehension is faster than iterated list.append
, thus:
results = [ item['value'] for item in test_data ]
Related Topics
After Getting Image from Uiimagepickercontroller, Uiimageview Rotates Image for iPhone 5
Swift Function Compiler Error 'Missing Return'
Replacing Multiple Different Occurences with Multiple Different Replacements - Swift4.2
Code Only Retrieving One Value from Data in Firebase
Accessing and Manipulating Array Item in an Environmentobject
Hiding Dividers in Nssplitview
How to Make a Variable from a String
How to Perform Conditional Segue
How to Comprehend the "First-Class Function" in Swift
Datefromstring() Returns Incorrect Date
Let User Save PDF Outside App in iOS Swift
Swift Why Isn't My Date Object That's (Equatable) Equal After Converting It to a String and Back
How Is a Global Variable Set to Private Understood in Swift
Is There a Neat Way to Represent a Fraction as an Attributed String
Core Data Update in Swift While Selecting Any Row in List Table View Not Working
How to Use Querystartingatvalue in My Searchcontroller to Search for Users