Get Element from Array of Dictionaries According to Key

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 to index(where:
  • filteredArrayUsingPredicate(predicate) has been renamed to filtered(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



Leave a reply



Submit