2023.2.5 今日分享内容:JavaScript 特殊数据结构转换 递归
需求:将下图 origin 通过函数转换成 result
//初始数据
let origin = {
a: ['start'],
b: ['start','center','end'],
c: ['center','end'],
}
//处理后生成的数据
let result = [
{ a: 'start', b: 'start', c: 'center' },
{ a: 'start', b: 'start', c: 'end' },
{ a: 'start', b: 'center', c: 'center' },
{ a: 'start', b: 'center', c: 'end' },
{ a: 'start', b: 'end', c: 'center' },
{ a: 'start', b: 'end', c: 'end' }
]
思考后整理的处理函数:
function fun(item, origin, keys, index){
//定义结果
let list = []
//获取当前处理的 key
let key = keys[index]
//获取当前 key 对应的 属性值
let vals = origin[key]
//遍历 当前 key 的属性值数组
for(let i = 0, len = vals.length; i < len; i++){
//浅拷贝 当前层级 item 对象
let copy = JSON.parse(JSON.stringify(item))
//浅拷贝对象 赋值
copy[key] = vals[i]
//如果 当前的key 是最后一个待处理属性 则将赋值后的对象添加到 结果中
if(index === keys.length - 1) list.push(copy)
//如果 当前的key 不是最后一个待处理的 key 则把新赋值的对象进行下一个 key 处理
else list.push(...fun(copy, origin, keys, index + 1))
}
//返回结果
return list
}
测试结果如下:
//执行函数
let result = fun({}, origin, Object.keys(origin), 0)
/**
* 生成的 result 结果如下
* result: [
* { a: 'start', b: 'start', c: 'center' },
* { a: 'start', b: 'start', c: 'end' },
* { a: 'start', b: 'center', c: 'center' },
* { a: 'start', b: 'center', c: 'end' },
* { a: 'start', b: 'end', c: 'center' },
* { a: 'start', b: 'end', c: 'end' }
* ]
*/