preface

A few days ago, I had a second interview with Ali. After the interview, I did two programming questions, one of which was about the flattening of objects. The details of the questions were as follows:

// Implement a flatten function that does the following conversion
const obj = {
  a: 1.b: [1.2, { c: true}].c: { e: 2.f: 3 },
  g: null};/ / convert
let objRes = {
  a: 1."b[0]": 1."b[1]": 2."b[2].c": true."c.e": 2."c.f": 3.g: null};Copy the code

flat

From the result, we can know that we need to traverse the object and output the property values in turn, so we can know that the core method body is: pass in the key value and value of the object, and recursively traverse the value.

We know that JS data types can be base data types and reference data types. As for the topic, there is no need for in-depth traversal of basic data types, while reference data types need to be recursed again.

The solution process is as follows:

let flatten = (obj) = > {
	let result = {};
    
    let process = (key, value) = > {
    	// Determine whether it is an underlying data type or a reference data type
        if (Object(value) ! == value) {// Base data type
            if(key) { result[key] = value; }}else if(Array.isArray(value)){
       		for (let i = 0; i< value.length; i++) {
            	process(`${key}[${i}] `, value[i])
            }
            if (value.length === 0) { result[key] = []; }}else {
        	let objArr = Object.keys(value);
            objArr.forEach(item= > {
            	process(key?`${key}.${item}`:`${item}`, value[item])
            });
            if (objArr.length === 0 && key) {
            	result[key] = {};
            }
        }
    }
    process(' ', obj)
    return result;
}

Copy the code

The following output is displayed:

I cried. I was too nervous. I was thinking right and I didn’t write the process well

Ok, the basic problem has been solved, now a little more advanced ~ ~

The flat

As the name suggests, the process is reversed