如果我有一个扁平的物体,那么这是有效的:
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
答案 0 :(得分:1)
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);
}
});
}
}
答案 1 :(得分:1)
似乎你可以用一点递归函数来做到这一点:
let state = {
left:{
start: "mark",
anotherLevel: {
test: 'leveltest'
}
},
test: "will be replaced"
}
let dictionary={
test2: {
foo: 'bar'
},
left:{
name:'WORK',
min:2,
sec:0,
anotherLevel: {
test_add: 'leveltest_add'
}
},
start:true,
test: 'replaced with me'
}
let stateCopy={...state}
function merge(obj, dict){
Object.entries(dict).forEach(([k, v]) =>{
if (!obj[k] || typeof v !== 'object') obj[k] = v
else merge(obj[k], v)
})
}
merge(stateCopy, dictionary)
console.log(stateCopy)