0

使用 javascript 我需要显示 JSON 结构中的属性 --> 变量值。我还需要显示中的类依赖项以及相应 JSON 结构的变量名。

我无法将正确的类依赖项与属性数组中的相应变量分开

{
"demo": {
    "class": [
        {
            "name": "class1",
            "attributes": [],
            "class": [
                {
                    "name": "class2",
                    "attributes": [
                        {
                            "variable": "firstname"
                        },
                        {
                            "variable": "lastname"
                        },
                        {
                            "variable": "middlename"
                        }
                    ]
                }
            ]
        },
        {
            "name": "class3",
            "attributes": [],
            "class": [
                {
                    "name": "class4",
                    "attributes": [],
                    "class": [
                        {
                            "name": "class5",
                            "attributes": [
                                {
                                    "variable": "city"
                                },
                                {
                                    "variable": "state"
                                },
                                {
                                    "variable": "country"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
  }
 }

输出应该像

    variable name                      class dependency

     firstname                          :class1:class2
     lastname                           :class1:class2
     middlename                         :class1:class2
     city                               :class3:class4:class5
     state                              :class3:class4:class5
     country                            :class3:class4:class5
4

1 回答 1

0

我让它工作了。我做了一个函数调用determine,它将返回一个包含每个键的标记的对象JSON

var determine = function ( obj ) {

    var result = {},
        index = 0,
        name;
        getData = function ( _obj, _result ) {

            var key;

            if ( 'name' in _obj ) {
                name += ':' + _obj.name;
            }

            if ( 'class' in _obj ) {

                _obj.class.forEach( function ( data ) {
                    getData( data, _result );
                });
                name = '';

            } else {

                for ( key in _obj.attributes ) {
                    _result[ _obj.attributes[ key ].variable ] = name.substr( 1 );
                }

            }

            return _result;

        };

    for ( var item in obj ) {

        name = '';
        result[ item ] = getData( obj[ item ], {} );
        index++;

    }

    return result;

};

var markup = determine( json );

console.log( markup );
于 2013-03-13T11:18:48.503 回答