有趣数据结构转化,如何实现?

原始数据
javascriptvarobj={
'a':1,
'b':2,
'c':['x','y','z','j'],
'd':['a','c','u'],
'e':['e','d']
};
转化为目标数据
javascript[
{'a':1,'b':2,'c':'x','d':'a','e':'e'},
{'a':1,'b':2,'c':'y','d':'a','e':'e'},
{'a':1,'b':2,'c':'z','d':'a','e':'e'},
{'a':1,'b':2,'c':'j','d':'a','e':'e'},
{'a':1,'b':2,'c':'x','d':'c','e':'e'},
{'a':1,'b':2,'c':'y','d':'c','e':'e'},
{'a':1,'b':2,'c':'z','d':'c','e':'e'},
{'a':1,'b':2,'c':'j','d':'c','e':'e'},
{'a':1,'b':2,'c':'x','d':'u','e':'e'},
{'a':1,'b':2,'c':'y','d':'u','e':'e'},
{'a':1,'b':2,'c':'z','d':'u','e':'e'},
{'a':1,'b':2,'c':'j','d':'u','e':'e'},
{'a':1,'b':2,'c':'x','d':'a','e':'d'},
{'a':1,'b':2,'c':'y','d':'a','e':'d'},
{'a':1,'b':2,'c':'z','d':'a','e':'d'},
{'a':1,'b':2,'c':'j','d':'a','e':'d'},
{'a':1,'b':2,'c':'x','d':'c','e':'d'},
{'a':1,'b':2,'c':'y','d':'c','e':'d'},
{'a':1,'b':2,'c':'z','d':'c','e':'d'},
{'a':1,'b':2,'c':'j','d':'c','e':'d'},
{'a':1,'b':2,'c':'x','d':'u','e':'d'},
{'a':1,'b':2,'c':'y','d':'u','e':'d'},
{'a':1,'b':2,'c':'z','d':'u','e':'d'},
{'a':1,'b':2,'c':'j','d':'u','e':'d'},
]
参数是不定的,
varobj1={
'a':1,
'b':2,
'c':['x','y','z','j'],
'd':['a','c','u'],
'e':['e','d']
}
varobj2={
'a':1,
'b':2,
'c':['x','y','z','j'],
'd':['a','c','u']
}
varobj3={
'c':['x','y','z','j'],
'd':['a','c','u']
}
varobj4={
'a':1,
'b':2
}
等等,对象个数没有限制,属性值没有限制(当然,只翻译属性值为数组类型的)
阿波罗的战车
浏览 291回答 2
2回答

慕莱坞森

javascriptfunctiontransform(obj,keys,index,result){varkey=keys[index];varvalue=obj[key];if(Array.isArray(value)){varnewObj={};varnewObj2={};keys.forEach(function(k){newObj[k]=k===key?value[0]:obj[k];newObj2[k]=k===key?value.slice(1):obj[k];});if(newObj[key]!==undefined){transform(newObj,keys,index,result);}if(newObj2[key].length>0){transform(newObj2,keys,index,result);}}else{if(index===keys.length-1){varret={};keys.forEach(function(k){ret[k]=obj[k];});result.push(ret);}else{transform(obj,keys,index+1,result);}}}varobj={'a':1,'b':2,'c':['x','y','z','j'],'d':['a','c','u'],'e':['e','d']};varresult=[];transform(obj,Object.keys(obj),0,result);result.forEach(function(o){console.log('%j',o);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript