json keyname map

zyip發表於2016-05-06

 

var obj = {
  fname:'zhao',
  lname:'yao',
  parents:{
    father:'zhao'    
  },
  children:[
    {
      dname:'zhaoyiyi'
    }
  ]
}

var hash={fname:'firstname',lname:'lastname',father:'fathername',dname:'dautername'}
function map(obj)
{
  var keys=Object.keys(obj);
  var hashKeys = Object.keys(hash);
  for(var i=0,j=keys.length;i<j;i++)
  {
    if(typeof obj[keys[i]]==='object')
    {
      if(obj[keys[i]].splice && obj[keys[i]].push)
      {
        for(var x=0,y=obj[keys[i]].length;x<y;x++)
        {
          obj[keys[i]][x]=map(obj[keys[i]][x]);
        }
      }
      obj[keys[i]] = map(obj[keys[i]]);
    }
    if(hash[keys[i]])
    {
      obj[hash[keys[i]]]=obj[keys[i]];
      delete obj[keys[i]];
    }
  }
  return obj;
}

console.log(map(obj));

 

相關文章