What can be done when multiple methods are combined in JavaScript
This article mainly introduces what can be done when many methods are combined in JavaScript. The introduction in this article is very detailed and has a certain reference value. Friends who are interested must read it!
What can be done when multiple methods are combined? (example 1)
Scene:
The data obtained from the front end is
Data = [{id: 1, name: 'level 1 title-1'}, {id: 2, name: 'level 1 title-2'}, {id: 3, name: 'level 2 title-1 title, pid: 1}, {id: 3, name:' level 1 title-3'}, {id: 3, name: 'level 2 title-2 title, pid: 2},]
We need to form and connect relationships, such as:
NeedData = [{id: 1, name: 'level 1 title-1 title, children: [{id: 3, name:' level 2 title-1 title, pid: 1}]}, {id: 2, name: 'level 1 title-2 title, children: [{id: 5, name:' level 2 title-2' Pid: 2}]}, {id: 4, name: 'first level title-3'},]
So I made use of several api provided by the array:
NewList = data.reduce ((result, item, _, arr) = > {if (! item.pid) {return [... result, item];} const parentItem = arr.find (({id}) = > id = item.pid); if (parentItem) {const {children = []} parentItem; parentItem.children = [... children, item];} return result;}, [])
Train of thought:
Look for elements that have a parent
Send it to the right location.
Returns all data without a parent field (pid)
The above is all the content of the article "what can be done with multiple methods in JavaScript?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!