首页 > 解决方案 > 如何获取嵌套对象的键

问题描述

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

 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 

标签: javascriptreact-native

解决方案


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

推荐阅读