我长期以来一直在使用 ember 数据,但我从来没有遇到过检查模型中是否存在 key 的情况。通常,我检查模型中的键是否存在值
if(model.get('keyname')) {
console.log('value present')
}
但现在我想检查模型对象中是否存在 key 。任何帮助将不胜感激。
忘记在这里提及 - 这里的模型是嵌入式记录,我的项目中没有用于该嵌入式记录的模型文件(我正在为嵌入式记录自动生成模型)。因此,我无法使用属性或字段。
最佳答案
您可以使用 attributes或 fields
说 app/models/person.js
import Model from "ember-data/model";
import attr from "ember-data/attr";
import { belongsTo, hasMany } from "ember-data/relationships";
export default Model.extend({
firstName: attr('string'),
relations: hasMany('person'),
});
属性
一个映射,其键是模型的属性(由 DS.attr 描述的属性),其值是属性的元对象。
import Ember from 'ember';
import Person from 'app/models/person';
let attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(meta, name) {
console.log(name, meta);
});
输出:
firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
字段
一个映射,其键是模型的字段,其值是描述字段类型的字符串。模型的字段是其所有属性和关系的联合。
import Ember from 'ember';
import Person from 'app/models/person';
let attributes = Ember.get(Person, 'fields')
attributes.forEach(function(meta, name) {
console.log(name, meta);
});
输出:
lastName attribute
users hasMany
关于javascript - 如何检查ember模型是否有 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43056839/