javascript - 如何获取嵌套对象的键
问题描述
如果我有一个平面物体,那么这有效:
let stateCopy={...this.state}
Object.entries(dictionary).map(([key,value])=>{
stateCopy.key = value.toString())
})
如果字典包含嵌套对象,有没有办法做到这一点。假设字典看起来像:
dictionary={left:{name:'WORK',
min:2,
sec:0,}
start:true}
我需要一些更新 stateCopy 的方法,即
stateCopy.left.name='WORK'
stateCopy.left.min=2
stateCopy.left.sec=0
stateCopy.start=true
解决方案
function flattenDictionary(dict) {
if (!dict) {
return {};
}
/** This will hold the flattened keys/values */
const keys = {};
// Perform the flatten
flattenH(dict);
return keys;
function flattenH(obj, prefix) {
Object.keys(obj).forEach((key) => {
const val = obj[key];
/** This is what we pass forward as a new prefix, or is the flattened key */
let passKey;
// Only expect to see this when the original dictionary is passed as `obj`
if (!prefix || prefix === '') {
passKey = key;
} else {
// "Ignore" keys that are empty strings
passKey = ((key === '') ? prefix : `${prefix}.${key}`);
}
if (typeof obj[key] !== 'object') {
keys[passKey] = val;
} else {
flattenH(val, passKey);
}
});
}
}
推荐阅读
- ruby-on-rails - Ruby 字符串不超过 n 个字符
- python - 对数据帧进行子集化以与 fmin 一起使用会产生意外错误
- javascript - Javascript String.charAt(i) 和 string[i] 给出不同的结果?
- html - HTML链接标签不同样式的速度
- r - 两组坐标之间的最小距离
- amazon-web-services - AWS Glue TypeError:+ 的不支持的操作数类型:“DynamicFrame”和“str”
- javascript - 无法将 FormModule 导入 Angular4 项目,ng.forms.FormModule 未定义
- c# - MySqlDataReader.GetSchemaTable ColumnOrdinal 是实际数据的 +1
- android - Android,制作一个相当复杂的动画?
- javascript - 如何解决此(不和谐)SQLite 错误