Frontend Development 7 min read

Practical JavaScript Techniques: Maps, Sets, Array.from, Destructuring, API Integration, and Tree Conversion

This article shares practical JavaScript snippets for managing dictionaries with Map, deduplicating arrays using Set, constructing data with Array.from, applying destructuring patterns, merging API modules in Vue projects, and converting flat data into tree structures, providing clear examples and reusable code.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Practical JavaScript Techniques: Maps, Sets, Array.from, Destructuring, API Integration, and Tree Conversion

Map Dictionary

During project development you may need configurable dictionaries or maintain common code tables; the following examples show two ways to define such maps, with the second variant often being more suitable.

/**
 * 计划周期  PLAN_LEVEL
 */
export const PLAN_LEVEL = new Map();
PLAN_LEVEL.set('1', '月度')
PLAN_LEVEL.set('2', '季度')
PLAN_LEVEL.set('3', '年度')

// 变异写法
export const APP_TYPE = new Map([
  ['APP', '应用'],
  ['LINK', '链接'],
  ['COM', '组件']
]);

Set Deduplication

Since ES6, deduplicating arrays has become straightforward using Set.

const unique = (arr) => Array.from(new Set(arr))
unique([1,2,3,6,6,7]) // [1,2,3,6,7]

Using spread syntax makes it even simpler, and Array.from also offers interesting alternatives.

const unique = (arr) => [...new Set(arr)]
unique([1,2,3,6,6,7]) // [1,2,3,6,7]

Array.from Data Construction

Construct an array of a specific length

Array.from({ length: 1000 })

Fill an array with a specific pattern

// Fill with 10
Array.from({ length: 1000 }).fill(10)

// Generate sequential numbers
Array.from({ length: 1000 }, (v, i) => i)

Destructuring

Destructuring brings many conveniences; here are two useful examples.

Example 1 (rest parameters excluding certain fields) : Adjust pagination parameters to match backend expectations.

var obj = { page: 1, size: 10, name: "测试", type: 1 }
const { page, size, ...other } = obj
// other = { name: '测试', type: 1 }
var newParam = { ...other, pageNo: page, pageSize: size }
// newParam = { name: '测试', type: 1, pageNo: 1, pageSize: 10 }

Example 2 (fixed‑length array destructuring) :

const [name, id] = "测试_01".split('_')
console.log(name, id) // 测试 01

API File Merging

When many business API modules are defined, an index.js can merge them into a single object for global injection, demonstrated with Vue.

Integration

/* 接口集成 */
const requireAPIS = require.context('./modules', false, /\.js$/)
const apis = {}
requireAPIS.keys().forEach(key => {
  let module = requireAPIS(key)
  if (module) {
    const name = key.replace(/(\.\/|\.js)/g, '')
    apis[name] = module
  }
})
export default apis

Registration

Vue.prototype.$api = apis;

Usage

async onSave() {
  // data saving
  const resp = await this.$api.user.saveConfig({})
}

Tree Structure Conversion

A utility function converts a flat list into a zTree‑compatible hierarchical format.

transformTozTreeFormat(sNodes, { key, parentKey, childKey }) {
  var i, l,
      key = key || 'id',
      parentKey = parentKey || 'pId',
      childKey = childKey || 'children';
  if (!key || key == "" || !sNodes) return [];
  if (Object.prototype.toString.apply(sNodes) === "[object Array]") {
    var r = [];
    var tmpMap = [];
    for (i = 0, l = sNodes.length; i < l; i++) {
      if (sNodes[i][childKey]) {
        delete sNodes[i][childKey];
      }
      tmpMap[sNodes[i][key]] = sNodes[i];
    }
    for (i = 0, l = sNodes.length; i < l; i++) {
      if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
        if (!tmpMap[sNodes[i][parentKey]][childKey])
          tmpMap[sNodes[i][parentKey]][childKey] = [];
        tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
      } else {
        r.push(sNodes[i]);
      }
    }
    return r;
  } else {
    return [sNodes];
  }
}

Calling the function:

var dt = transformTozTreeFormat(res, { key: "id", parentKey: "parentId" });

Appendix

💪 Jump out of frantic busyness

💪 Don't misplace persistence; clash of two mindsets

💪 Discuss horizontal capabilities through online issues

💪 I have a knife that can cut the full stack

💪 The problem of shoes not fitting at 35

💪 What is core competitiveness

If this article helped you, feel free to follow, like, and collect.

JavaScriptVuemapsetDestructuringArray.from
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.