Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What can be done when multiple methods are combined in JavaScript

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report