gpt4 book ai didi

javascript - 如何获取嵌套对象的键

转载 作者:行者123 更新时间:2023-12-01 02:07:20 30 4
gpt4 key购买 nike

如果我有一个扁平的物体,那么这有效:

 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);
}
});
}
}

关于javascript - 如何获取嵌套对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50009223/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com