JS object to array

MDN details:

The object.entries () method returns an array of key-value pairs for the given Object’s own enumerable properties, arranged in the same order as for… The in loop returns the same order as it iterates through the object (the difference is that for-In also enumerates the properties in the prototype chain).

The array.prototype. map method creates a new Array with the result that each element in the Array is the value returned by calling the provided function once.

If we have data for a city that records some value for the city, the back end typically returns a simple data format such as:

let cityObj = {
    shenzhen: 31.guangzhou: 29
}
Copy the code

If we want to use it in pie charts, we need to change cityObj to array format cityArr, as in:

let cityArr = [
  {cityName: 'shenzhen', value: 31},
  {cityName: 'guangzhou', value: 29}
]
Copy the code

If there are few attributes, you can manually assign them to an array format using., as in:

let cityArr = [
  {cityName: 'shenzhen'.value: cityObj.shenzhen},
  {cityName: 'guangzhou'.value: cityObj.guangzhou}
]
Copy the code

But if there are a lot of cities, or even all of China, then you’ll look muggle if you use. So it’s recommended to use traversal, or you can wrap the thing up and add your own utility functions.

Here are two ways to do this.

useObject.entries + Array.prototype.mapObject to array

let cityObj = { // Object data
  shenzhen: 31.guangzhou: 29
}
/ / packaging
function objToArr(data, typeName, valueName) {
  // object. entries(data) convert data into [[key, value],...]
  Map (([typeName, valueName]) => ({typeName, valueName})) Deconstructs [key, value]
  // Then return {typeName: typeName, valueName: valueName}

  return Object.entries(data).map(([typeName, valueName]) = > ({typeName, valueName}))
}

/ / execution
objToArr(cityObj, 'cityName'.'value')
Copy the code

useObject.keys + Array.prototype.mapObject to array

let cityObj = { // Object data
  shenzhen: 31.guangzhou: 29
}

/ / packaging
function objToArr(data, typeName, valueName) {
  Key (key, key, key...); // Object. Keys (data)
  // .map(key => ({typeName: key, valueName: data[key]})) 
  // select key and value data[key];
  // Then return {typeName: typeName, valueName: valueName}

  return Object.keys(data).map(key= > ({typeName: key, valueName: data[key]}))
}

objToArr(cityObj, 'cityName'.'value')
Copy the code

JS array to object

MDN details:

The object. fromEntries method converts the list of key-value pairs to an Object.

The array.prototype. map method creates a new Array with the result that each element in the Array is the value returned by calling the provided function once.

If we need to pass the data cityArr on the pie chart to the back end, generally the data will be simplified to cityObj, such as:

let cityArr = [
  {cityName: 'shenzhen', value: 31},
  {cityName: 'guangzhou', value: 29}
]
let cityObj = {
    shenzhen: 31,
    guangzhou: 29
}
Copy the code

Since there are object. entries and object. fromEntries, you can use Object.fromEntries + array.prototype. map to convert the format

useObject.fromEntries + Array.prototype.mapArray to object

let cityArr = [ // Array data
  { cityName: 'shenzhen'.value: 31 },
  { cityName: 'guangzhou'.value: 29}]/ / packaging
function arrToObj(data, typeName, valueName) {
  // data.map(item => ([item.typename, item.valuename]));
  // object.fromentries () equals the inverse method of Object.entries()
  // Then return {typeName: valueName}

  return Object.fromEntries(data.map(item= > ([item[typeName], item[valueName]])))
}

arrToObj(cityArr, 'cityName'.'value')
Copy the code

JS one-dimensional array conversion, tree structure array conversion

If it is useful to the permission tree or file module, it is generally necessary to take back data from the back end to do a one-dimensional array to tree structure, or transfer to the back end of the tree structure to a flat array, unless you have an intimate relationship with the back end, otherwise these are the front end to do their own processing.

For example, we need to convert dataArr to dataTree

let dataArr = [
  { id: 1.pid: 0 },
  { id: 2.pid: 1}]let dataTree = [
  {
    id: 1.pid: 0.children: [{id: 2.pid: 1
        children: []}]}]Copy the code

Recursive method transforms tree structure data

  • Large amount of calculation
  • It doesn’t change the original data
let data = [ // If the back end has no intimate relationship with you, the data you get is a list
  { id: 1.pid: 0 },
  { id: 2.pid: 0 },
  { id: 3.pid: 1 },
  { id: 4.pid: 2 },
  { id: 5.pid: 3 },
  { id: 6.pid: 4 },
  { id: 7.pid: 5 },
  { id: 8.pid: 6},]function arrToTreeData(data, pidVal = 0, pidName = 'pid', childName = 'children') {
  // pid is the parentId, which is pid by default
  // When pidVal is 0, the default is the root node
  // childName is usually named children in most tables, multilevel nesting, etc. The default is children
  let result = [] / / initialization

  // Recursive matching, large amount of calculation
  data.forEach(item= > {
    if(item[pidName] === pidVal) { result.push({ ... item, [childName]: arrToTreeData(data, item.id) }) } })return result
}

arrToTreeData(data)
Copy the code

Object reference method to tree structured data

  • A small amount of calculation
  • Not using deep copy changes the original data
let data = [ // If the back end has no intimate relationship with you, the data you get is a list
  { id: 1.pid: 0 },
  { id: 2.pid: 0 },
  { id: 3.pid: 1 },
  { id: 4.pid: 2 },
  { id: 5.pid: 3 },
  { id: 6.pid: 4 },
  { id: 7.pid: 5 },
  { id: 8.pid: 6},]function arrToTreeData(data, pidName = 'pid', childName = 'children') {
  // pid is the parentId, which is pid by default
  // childName is usually named children in most tables, multilevel nesting, etc. The default is children
  let obj = {} / / initialization
  let result = [] / / initialization

  // Store the data as an object
  data.forEach(item= > {
    obj[item.id] = item
  })

  for (let i = 0; i < data.length; i++) {
    let item = data[i]
    // if obj is not found, undefined, this item is the root
    let parent = obj[item[pidName]] 
    if (parent) {
      (parent[childName] || (parent[childName] = [])).push(item)
    } else {
      result.push(item)
    }
  }

  return result
}

arrToTreeData(data)
Copy the code

Breadth method flattening tree structure data

  • Not using deep copy changes the original data
function cutTree(data, childName = 'children') {
  let result = [];

  while(data.length ! =0) {
    let shift = data.shift();
    let children = shift[childName]
    delete shift[childName]
    result.push(shift)

    if (children) {
      children.forEach(item= > {
        data.push(item)
      })
    }
  }
  return result
}
Copy the code