2 回答
TA贡献1875条经验 获得超3个赞
您可以通过避免不需要的循环属性来对数据进行分组。
const
data = [{ country: "USA", state: "FLORIDA", city: "city1" }, { country: "USA", state: "FLORIDA", city: "city2" }, { country: "USA", state: "FLORIDA", city: "city3" }, { country: "USA", state: "ALASKA" }, { country: "USA", state: "ALBAMA" }],
keys = ['country', 'state', 'city'],
result = data.reduce((loop, o) => {
keys
.map(k => o[k])
.filter(Boolean)
.reduce((r, value) => {
let temp = (r.loop ??= []).find(q => q.value === value);
if (!temp) r.loop.push(temp = { sequence: r.loop.length + 1, value });
return temp;
}, { loop });
return loop;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1830条经验 获得超9个赞
你可以写你的transform
使用flatMap
和递归 -
const transform = ([ name, ...more ], { value, loop = [{}] }, r = {}) =>
name === undefined
? [ r ]
: loop.flatMap(t => transform(more, t, { [name]: value, ...r }))
const records =
{sequencer:1,value:'USA',loop:[{sequencer:1,value:'FLORIDA',loop:[{sequencer:1,value:'city1'},{sequencer:2,value:'city2'},{sequencer:3,value:'city3'}]},{sequencer:2,value:'ALASKA'},{sequencer:3,value:'ALBAMA'}]}
const columns =
['country', 'state', 'city']
const result =
transform(["country", "state", "city"], records)
console.log(JSON.stringify(result, null, 2))
function等同于上述表达式的语句=>-
function transform
( [ name, ...more ]
, { value, loop = [{}] }
, r = {}
)
{ if (name === undefined)
return [ r ]
else
return loop.flatMap
( t =>
transform
( more
, t
, { [name]: value, ...r }
)
)
}
添加回答
举报