A,

  1. String parsing into executable variables, listening to data changes easily and quickly, analogyVueWatch is a string.
  2. Processing interface data fault tolerance rate, chain selection error reporting a solution.
  3. Quickly set up data objects.

Second, the code

// ./strToJSON.js

/ * * *@descriptionParse a string into a JSON string *@param {*} STR string *@param {*} * | object obj array@param {*} Val values *@return {*} To obtain the value of | after setting the value of * /

const delArrList = (arr = [], arrList = [], val, flag) = > {
  const li = arrList.shift()
  if (arrList.length > 0) {
    if (arr[li]) {
      return delArrList(arr[li], arrList, val, flag)
    }
  }
  
  if(val ! = =undefined && flag) {
    arr[li] = val
  }
  return arr[li]
}

const delArr = (arr = [], obj = {}, val, flag) = > {
  if (arr[0].indexOf('[') > -1) {
    const left = arr[0].split('[')
    const arrList = []
    left.forEach(v= > {
      if (v.indexOf('] ') > -1) {
        const right = v.split('] ')
        arrList.push(right[0])}})return delArrList(left[0]? obj[left[0]] : obj, arrList, val, flag)
  }

  if(val ! = =undefined && flag) {
    obj[arr[0]] = val
  }
  return obj[arr[0]]}export const getStrJSON = (str, obj, val) = > {
  const arr = str.split('. ')
  if (arr.slice(1).length > 0) {
    const newStr = arr.slice(1).join('. ')
    const ret = delArr(arr, obj, val)
    if (ret) {
      return getStrJSON(newStr, ret, val)
    }
  } else {
    return delArr(arr, obj, val, true)}}export const setStrJSON = (str, obj, val) = > {
  const newObj = JSON.parse(JSON.stringify(obj))
  getStrJSON(str, newObj, val)
  return newObj
}
Copy the code

Three, use examples

  1. Get the value

    import { getStrJSON } from './strToJSON.js'
    
    const str = 'a[1][0][0].d[0].c'
    const str2 = 'a[1][0][0].e.c'
    const obj = { a: [{ b: [[{{}},d: [{ c: { e: [54] } }] }]]] }
    
    getStrJSON(str, obj) // { e: [54] }
    getStrJSON(str2, obj) // undefined # will not return an error
    Copy the code
  2. Set the value

    import { setStrJSON } from './strToJSON.js'
    
    const str = 'a[1][0][0].d[0].c'
    const str2 = 'a[1][0][0].d[2]'
    const obj = { a: [{ b: [[{{}},d: [{ c: { e: [54] } }] }]]] }
    
    setStrJSON(str, obj, { abc: 23 }) / / {a: [{b: {}}, [[{d: [] {c: {ABC: 23}}}]]]} # will not change the original object obj
    setStrJSON(str2, obj, { abc: 23 }) // {"a":[{"b":{}},[[{"d":[{"c":{"e":[54]}},null,{"abc":23}]}]]]}
    Copy the code