Я бы использовал Object.entries()
и Array.find()
для этого.
const data = {
"barID1": {
"address": "4 East Terrace, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "description text",
"imgURLs": [ "Https:url1", "https:url2", "https:url3" ],
"lat": -34.810585,
"lon": 138.616739,
"name": "Africola",
"phone": "(08) 8223 3885",
"status": "active",
"venueImgURL": "https:url"
},
"barID2": {
"address": "138/140 Gouger St, Sydney NSW 2000",
"appStoreURL": "http://itunes.apple.com/app/idXXXXXXXXX",
"description": "description text",
"imgURLs": [ "Https:url1", "https:url2", "https:url3" ],
"lat": -34.848082,
"lon": 138.599813,
"name": "Disco Mexico Taqueria",
"phone": "0416 855 108",
"status": "active",
"venueImgURL": "https:url"
}
};
const [key, obj] = Object.entries(data).find(([key, obj]) => {
return obj.name === 'Africola';
});
console.log(key, obj);
Fiddle: https://jsfiddle.net/zty6fgcp/
I just had to answer this, cos it's a fun Ruby excercise.
Adding methods to a class can be done many ways, but one of the neatest ways is to use some of the reflection and evaluation features of Ruby.
Create this file in your lib folder as lib/date_methods.rb
module DateMethods
def self.included(klass)
# get all dates
# Loop through the class's column names
# then determine if each column is of the :date type.
fields = klass.column_names.select do |k|
klass.columns_hash[k].type == :date
end
# for each of the fields we'll use class_eval to
# define the methods.
fields.each do |field|
klass.class_eval <<-EOF
def formatted_#{field}
#{field} ? #{field}.to_s(:date) : nil
end
EOF
end
end
end
Now just include it into any models that need it
class CourseSection < ActiveRecord::Base
include DateMethods
end
When included, the module will look at any date columns and generate the formatted_ methods for you.
Learn how this Ruby stuff works. It's a lot of fun.
That said, you have to ask yourself if this is necessary. I don't think it is personally, but again, it was fun to write.
-b-
Для меня это больше похоже на помощника. Попробуйте это в справке по вашему приложению:
def formatted_date(date)
date ? date.to_s(:date) : nil
end
Форматирование - это не то, что действительно относится к модели (именно по той причине, которую вы обнаружили ... использование такого общего кода в каждой модели раздражает)
Если вы хотите сделать то, что вы говорите, то вы могли бы исправить суперкласс ActiveRecord и добавить туда нужную функцию. Тогда он будет доступен для всех ваших моделей. Помните, что исправление обезьян может привести к непредсказуемому и неопределенному поведению, и используйте его на свой страх и риск! Это также довольно хакерский метод :)
class ActiveRecord::Base
def formatted_start_date
start_date ? start_date.to_s(:date) : nil
end
end
Просто закрепите то, что будет запущено раньше, чем что-либо еще в вашем приложении, и оно будет динамически добавлять метод в базовый класс ваших моделей, делая его доступным для использования.
Ответ на ваш комментарий: Вы можете выделить общий код / функциональность в модули, которые вы включаете в класс (я полагаю, это называется миксином?), Или вы можете использовать подклассы. Я не думаю, что подкласс - это то, что нужно, когда его просто общие функции, которые вы хотите использовать в своих объектах, а не реальная ситуация наследования.
Взгляните на this для получения дополнительной информации о модулях и Ruby .