D
D
Darkness2019-12-19 14:06:17
JavaScript
Darkness, 2019-12-19 14:06:17

How to do recursion with a large nesting of objects?

Problem :
Sometimes a large number can come. data, and maybe go further into objects, I don’t understand how to properly parse them with recursion:

"extra_data":{
    "city": {"type":"г","value":"Самара","fias_id":"bb035cc3-1dc2-4627-9d25-a1bf2d4b936b","full_type":"город","value_with_type":"г Самара"},
    "region": {"code":"63","type":"обл","value":"Самарская","fias_id":"df3d7359-afa9-4aaa-8ff9-197e73906b1c","full_type":"область","value_with_type":"Самарская обл"}
}

Stack :
vue.js
My code , which gives me 2 times, and does not go beyond 1 property.
I use in methods
setExtraFields() {
      let a = []
      _.forEach(this.lead.extra_data, (val, key) => {
          getProp(this.lead.extra_data)
      })

      function getProp(o) {
        for(var prop in o) {
          if(typeof(o[prop]) === 'object') {
            getProp(o[prop])
          } else {
            let rusTitle = cyrillicToTranslit().reverse(prop)
            let obj = {"title": rusTitle, "value": o[prop]}
            // тут хочу закинуть в массив объекты, который потом буду использовать с v-for
            return a.push(obj)
          }
        }
      }
      console.log(a)
    }

<b>console</b>
0: {title: "тыпе", value: "г"}
1: {title: "cоде", value: "63"}
2: {title: "тыпе", value: "г"}
3: {title: "cоде", value: "63"}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Darkness, 2019-12-20
@AntonBrock

Here is a working function that iterates over objects and adds them correctly into one array:

let a = []
getProp(this.n)
   function getProp(data) {
     let obj = {}
       _.forEach(data, (val, key) => {
          if (_.isObject(val)) {
             getProp(val);
          } else {
              a.push({"title": key, "value": val})
        }
      })
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question