循环遍历一组对象

时间:2016-07-11 03:45:19

标签: javascript arrays object

我有一个名为res的对象数组,我试图循环并根据一个href,一个方法,在某些情况下多个模式组织对象,如: href: '/questions/{id}'

我的问题是当我有多个模式时,如果我所在的当前对象具有'$ schema',我想检查数组中的下一个对象是否也有'$ schema'。如果是,那么我想标记当前的模式对象requestSchema,下一个对象将被称为responseSchema。但是如果下一个对象不包含'$ schema',那么当前对象将被标记为responseSchema。

我想拿res并把它变成

[{
        "resource": "/questions",
        "verb": "GET",
        "schemaResponse": {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
                "data": {
                    "type": "array",
                    "items": [{
                        "type": "object",
                        "properties": {
                            "question": {
                                "type": "string",
                                "enum": [
                                    "Favourite programming language?"
                                ]
                            },
                            "published_at": {
                                "type": "string",
                                "enum": [
                                    "2014-11-11T08:40:51.620Z"
                                ]
                            },
                            "url": {
                                "type": "string",
                                "enum": [
                                    "/questions/1"
                                ]
                            },
                            "choices": {
                                "type": "array",
                                "items": [{
                                    "type": "object",
                                    "properties": {
                                        "choice": {
                                            "type": "string",
                                            "enum": [
                                                "Javascript"
                                            ]
                                        },
                                        "url": {
                                            "type": "string",
                                            "enum": [
                                                "/questions/1/choices/1"
                                            ]
                                        },
                                        "votes": {
                                            "type": "number",
                                            "enum": [
                                                2048
                                            ]
                                        }
                                    },
                                    "required": [
                                        "choice",
                                        "url",
                                        "votes"
                                    ],
                                    "additionalProperties": false
                                }]
                            }
                        },
                        "required": [
                            "question",
                            "published_at",
                            "url",
                            "choices"
                        ],
                        "additionalProperties": false
                    }]
                }
            },
            "required": [
                "data"
            ]
        }
    }, {
        "resource": "/questions/{id}",
        "verb": "GET",
        "schemaRequest": {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
                "id": {
                    "type": "number"
                }
            },
            "required": [
                "id"
            ]
        },
        "schemaResponse": {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
                "question": {
                    "type": "string",
                    "enum": [
                        "Favourite programming language?"
                    ]
                },
                "published_at": {
                    "type": "string",
                    "enum": [
                        "2014-11-11T08:40:51.620Z"
                    ]
                },
                "url": {
                    "type": "string",
                    "enum": [
                        "/questions/1"
                    ]
                },
                "choices": {
                    "type": "array",
                    "items": [{
                        "type": "object",
                        "properties": {
                            "choice": {
                                "type": "string",
                                "enum": [
                                    "Javascript"
                                ]
                            },
                            "url": {
                                "type": "string",
                                "enum": [
                                    "/questions/1/choices/1"
                                ]
                            },
                            "votes": {
                                "type": "number",
                                "enum": [
                                    2048
                                ]
                            }
                        },
                        "required": [
                            "choice",
                            "url",
                            "votes"
                        ],
                        "additionalProperties": false
                    }]
                }
            },
            "required": [
                "question",
                "published_at",
                "url",
                "choices"
            ],
            "additionalProperties": false
        }

    }

]

除了需要具有请求模式和响应模式之外,一切都有效。

const lodash = require('lodash');

var res =  [ 
    { href: '/questions' },
    { method: 'GET' },
    { '$schema': 'http://json-schema.org/draft-04/schema#',
      type: 'object',
      properties: { data: [Object] },
      required: [ 'data' ] },
    { href: '/questions/{id}',
      hrefVariables: { element: 'hrefVariables', content: [Object] } },
    { method: 'GET',
      headers: { element: 'httpHeaders', content: [Object] } },
    { '$schema': 'http://json-schema.org/draft-04/schema#',
      type: 'object',
      properties: { id: [Object] },
      required: [ 'id' ] },
    { '$schema': 'http://json-schema.org/draft-04/schema#',
      type: 'object',
      properties: 
        { question: [Object],
          published_at: [Object],
          url: [Object],
          choices: [Object] },
      required: [ 'question', 'published_at', 'url', 'choices' ] } ]


    var arr = [];
    var arrFinal = [];
    var result = {};
    for (var key = 0; key < res.length; key++) {
        console.log(res[key]);
        console.log(key);

        var found = false;
        for(var i = 0; i < arr.length; i++) {
            //console.log((lodash.has(res[key], 'href')));
            //console.log((lodash.has(res[key-1], '$schema')));   
            if ((lodash.has(arr[i], 'href'))) {
                found = true;
                break;
            }
        }

        if ((lodash.has(res[key], '$schema')) && (lodash.has(res[key-1], '$schema'))) {
                console.log('here');
                result.schemaResponse = res[key];
                result = lodash.omit(result, ['headers', 'properties', 'hrefVariables', 'required', 'href', 'method']);
                break;


        }

        if((found === true) && (lodash.has(res[key], '$schema'))) {

            var result = {};   
            console.log('there') 
            var combinedKeys = arr.reduce(function(a, item) {
                Object.keys(item).map(function(key) {
                     if(key === 'href'){
                        result.resource = item[key];
                    }
                    if(key === 'method'){
                        result.verb = item[key];
                    } else {
                        result[key] = item[key];
                    }        

                });
                return result;
            }, {});
            arr = [];

            if((lodash.has(res[key+1], '$schema'))){
                result.schemaRequest = res[key];
            } else {
                result.schemaResponse = res[key];
                result = lodash.omit(result, ['headers', 'properties', 'hrefVariables', 'required', 'href', 'method']);
                arrFinal.push(result);
                result = {};
            }


        }

         else {
            console.log('hmmm');
            var object = res[key];
            arr.push(object); 

        }
    }

    var string = JSON.stringify(arrFinal, null, '  ')
    console.log(arrFinal)

1 个答案:

答案 0 :(得分:1)

基于此:

  

我的问题是当我有多个架构时,如果我所在的当前对象具有&#39; $ schema&#39;我想检查数组中的下一个对象是否也有&#39; $ schema&#39;。如果是,那么我想标记当前的模式对象requestSchema,下一个对象将被称为responseSchema。但是如果下一个对象不包含&#39; $ schema&#39;然后将当前对象标记为responseSchema。

和(从我对你的问题的评论):

  

你的问题有点不清楚(我建议再次校对并分解一些连续的句子)。当你评估是否((lodash.has(res [key],&#39; $ schema&#39;))&amp;&amp;(lodash.has(res [key-1],&#39; $ schema&#39;)))值res [key-1]总是未定义?所以基本上第二个if块永远不会执行

以下是一些适用于您的代码的伪代码:

 for ( var nIdx, crnt, next, key = 0, m = res.length; key < m; key++ ){
     crnt = res[ key ]
     next = res[ key + 1 ]

     //do your checking here based on the existence of 'next'
     if (next){ .... }
}

我在一个简单的循环中对此进行测试并记录crntnext的值,看看您是否真正获得了预期的结果。如果它们符合预期,您可以调整代码以使用这些值,而不是尝试使用代码中的res[ key ]动态访问它们。

我不知道,你的代码究竟是什么问题,但这至少会更具可读性,并可能说明你的错误。