---
description: for of 很好用，記得常用 for(const [key, value] of Object.entries(obj))
---

# Flatten Array/Object

[Codepen](https://codepen.io/hannahpun/pen/MdEVER?editors=1010)

### Flatten one level array

```
/**
 * @param {number[]} arr
 * @return {number[]}
 */
var flatten = function(arr) {}
```

```
Example 1:

Input:  [1, 2, [5, 6]]
Output: [1, 2, 5, 6]
```

#### Solution 1

若是純數字就放進新 Array，若不是則在做一次

```

var flatten = function(arr) {
  let newArr = [];
  convert(arr);
  
  function convert(lists) {
    lists.forEach(list => {
      if( !Array.isArray(list) ){
        newArr.push(list)
      } else{
        convert(list);
      }
    })
   }
   
   return newArr;
}

console.log(flatten([1, 2, [5, 6, [7, 8]]]))
```

#### Solution 2

比較簡潔的做法，使用 reduce. previous 被我初始化會是 \[]

```
[].concat(1) // [1]
[1, 2].concat[3, 4] // [1, 2, 3, 4]
```

```
var flatten = (lists) => lists.reduce((previous, cur) => previous.concat(cur), [])
```

### Flatten multiple level array

```
/**
 * @param {[] || number[]} arr
 * @return {number[]}
 */
var flattenMultiple = function(arr) {}
```

```
Example 1:

Input – [ 2, 3 , [ 4, 5, 6, [ 7 ], 8 ], 9]  
Output – [ 2, 3, 4, 5, 6, 7, 8, 9 ]

Example 2:
Input  – [ 2, 3, 4, 5, [6] ]   
Output – [ 2, 3, 4, 5, 6 ]
```

### Flatten object

```
/**
 * @param {object} arr
 * @return {object}
 */
var flattenObj = function(arr) {}
```

```
Example 1:

Input
{
  name: "Vishal",
  address: {
    primary: {
      house: "109",
      street: {             
        main: "21",
        cross: "32"
      }
    }
  }
};
Output
{
  user_name: "Vishal",
  user_address_primary_house: "109",
  user_address_primary_street_main: "21",
  user_address_primary_street_cross: "32",
}

```

其實跟 Array 大同小異，只差在 key 的部分

```
let newObj = {};
var flatten = function(obj, keyName) {

  for(const [key, value] of Object.entries(obj)){
     if(typeof value !== 'object'){
       newObj[`${keyName}_${key}`] = value;
    } else{
      flatten(value, `${keyName}_${key}`);
    }
  }
  
  return newObj;

}

console.log(flatten(user, 'user'))
```

### DOM

```
let data = {
  "Fish": {
    "trout": {},
    "salmon": {}
  },

  "Tree": {
    "Huge": {
      "sequoia": {},
      "oak": {}
    },
    "Flowering": {
      "apple tree": {},
      "magnolia": {}
    }
  }
};
```

![](https://1787585077-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LqirD3iAZIDk4oDCfwS%2Fuploads%2F6TYgD16ZjUoxpxts7sde%2FScreen%20Shot%202021-10-20%20at%2011.01.45%20PM.png?alt=media\&token=93a0f15d-5aa0-4a71-ac68-8cfdd92abd5b)

```
function createTree (data) {
  
  
  function createTreeDOM( data){ 
    let ul = document.createElement('ul');
    
    
    if(!Object.keys(data).length) return '';

    for(const [key, value] of Object.entries(data)){
      let li = document.createElement('li');
      li.textContent = key;

      li.append(createTreeDOM(value))
      ul.append(li) 
    }   
    
    return ul;
    
  }
  container.append( createTreeDOM(data) )
 
  
}
print(input)
```
