diff --git a/include/cantera/base/AnyMap.h b/include/cantera/base/AnyMap.h index 9c33d510f..332a01843 100644 --- a/include/cantera/base/AnyMap.h +++ b/include/cantera/base/AnyMap.h @@ -103,6 +103,18 @@ public: template std::map asMap() const; + //! Access a vector as a mapping using the value of `name` from each + //! item as the key in the new mapping. + /*! + * For example, for the list: + * ``` + * [{name: O2, weight: 32}, {name: CH4, weight: 16}] + * ``` + * calling `asMap("name")` will create a map with keys ``O2`` and ``CH4``. + */ + std::unordered_map asMap(const std::string& name) const; + std::unordered_map asMap(const std::string& name); + //! @see AnyMap::applyUnits void applyUnits(const UnitSystem& units); diff --git a/src/base/AnyMap.cpp b/src/base/AnyMap.cpp index b2e728222..1847531bc 100644 --- a/src/base/AnyMap.cpp +++ b/src/base/AnyMap.cpp @@ -361,6 +361,33 @@ AnyValue& AnyValue::operator=(AnyMap&& value) { return *this; } +std::unordered_map AnyValue::asMap( + const std::string& name) const +{ + std::unordered_map mapped; + for (const auto& item : asVector()) { + auto key = item.at(name).asString(); + if (mapped.count(key)) { + throw CanteraError("AnyValue::asMap", "Duplicate key '{}'", key); + } + mapped.emplace(std::make_pair(key, &item)); + } + return mapped; +} + +std::unordered_map AnyValue::asMap(const std::string& name) +{ + std::unordered_map mapped; + for (auto& item : asVector()) { + auto key = item.at(name).asString(); + if (mapped.count(key)) { + throw CanteraError("AnyValue::asMap", "Duplicate key '{}'", key); + } + mapped.emplace(std::make_pair(key, &item)); + } + return mapped; +} + void AnyValue::applyUnits(const UnitSystem& units) { if (is()) {