JSON.stringify replacer - how to get full path

后端 未结 5 1991
太阳男子
太阳男子 2021-01-07 07:35

Replacer in below code write on console current processed field name

5条回答
  •  無奈伤痛
    2021-01-07 08:23

    Something like that. You need to adjust it for arrays. I think that you can do it yourself. The idea is clear.

    let a = { a1: 1, a2:1 }
    let b = { b1: 2, b2: [1,a] }
    let c = { c1: 3, c2: b }
    
    function iterate(obj, path = '') {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], path + property + '.');
                }
                else {
                    console.log(path + property);
                }
            }
        }
    }
    
    iterate(c)

提交回复
热议问题