First, the flattening of objects

The inputs and outputs are as follows

const source = { a: { b: { c: 1.d: 2 }, e: 3 }, f: { g: 2}}console.log(objectFlat(source));
const obj = {
  a: 1.b: [1.2, { c: true}].c: { e: 2.f: 3 },
  g: null};console.log(objectFlat(obj)); -- -- -- -- -- -- -- -- the results {'a.b.c': 1.'a.b.d': 2.'a.e': 3.'f.g': 2 }
{
  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.

function objectFlat(obj = ' '){
  const res = {}
  function flat(item , preKey = ' '){
    Object.entries(item).forEach(([key,value]) = > {
      let newKey = key
      // console.log(value,typeof value,Array.isArray(value))
      if (Array.isArray(item)){
        // console.log(' is an array ')
        newKey = preKey ? `${preKey}[${key}] ` : key
      }else{
        newKey = preKey ? `${preKey}.${key}` : key
      }
      if (value && typeof value === 'object'){
        flat(value , newKey)
      }else{
        res[newKey] = value
      }
    })
  }
  flat(obj)
  return res
}

const source = { a: { b: { c: 1.d: 2 }, e: 3 }, f: { g: 2}}console.log(objectFlat(source));
const obj = {
  a: 1.b: [1.2, { c: true}].c: { e: 2.f: 3 },
  g: null};console.log(objectFlat(obj));
Copy the code

The advancedThe flat

A bit hasty, this section is not completely flat object. I’m going to flatten the resolution value and I don’t want to do coding

Go straight to code


function testPropTypes(value, type, dev) {
  const nEnums = [
    '[object Number]'.'[object String]'.'[object Boolean]'.'[object Undefined]'.'[object Function]'.'[object Null]'.'[object Object]'.'[object Array]'.'[object Date]'.'[object RegExp]'.'[object Error]',];const reg = new RegExp('\\[object (.*?)\\]');

  [object Window] [object HTMLDocument]...
  if (reg.test(type)) {
    // Exclude 12 types of nEnums
    if (~nEnums.indexOf(type)) {
      if (dev === true) {
        console.warn(value, 'The parameter Type belongs to one of 12 types: number string boolean undefined Null Object Array Date RegExp function Error NaN'); }}if (Object.prototype.toString.call(value) === type) {
      return true;
    }

    return false; }}function getValue(obj, key, defaultValue) {
  // Result variable
  const defaultResult = defaultValue === undefined ? undefined : defaultValue;

  if (testPropTypes(obj, 'Object') = = =false && testPropTypes(obj, 'Array') = = =false) {
    return defaultResult;
  }

  // The result variable, which temporarily points to a reference held by OBj, may be modified over time
  let result = obj;

  // Get the known value
  try {
    // Parse the attribute hierarchy
    const keyArr = key.split('. ');
    // console.log(keyArr[0])
    var res = []
    for (let i = 0; i < keyArr.length; i++) {
      let k0 = keyArr[i]
      // console.log(k0.split('['))
      k0 = k0.split('[')
      for (let i = 0; i < k0.length; i++) {
        if(k0[i] ! = =' ') {
          res.push(k0[i][0])}}}console.log(res)
    // Iterate over obj object properties
    for (let i = 0; i < res.length; i++) {
      // Iterate over the level I attribute if it has a value
      if(result[res[i]] ! = =undefined) {
        result = result[res[i]];

        // Return undefined if it does not exist
      } else {
        returndefaultResult; }}}catch (e) {
    return defaultResult;
  }

  // Returns the obtained result
  return result;
}

/ / sample
var object = { a: [{ b: { c: 3}}};// path: 'a[0].b.c'
var array = [{ a: { b: [1]}}];// path: '[0].a.b[0]'r
// res = 'a'

// function getValue(target, valuePath, defaultValue) {}

console.log(getValue(object, "a[0].b.c".0)); 3 / / output
console.log(getValue(array, "[0].a.b[0]".12)); / / output 1
console.log(getValue(array, "[0].a.b[0].c".12)); / / output 12
Copy the code

Remove chips