javascript - 循环遍历对象数组

标签 javascript arrays object

我有一个名为 res 的对象数组,并尝试根据一种 href、一种方法以及在某些情况下使用多个架构来循环和组织对象,如下所示: href: '/questions/{id}'

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

我想获取资源并将其变成

[{
        "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)

最佳答案

基于此:

My issue is when I have multiple schema, if the current object I am in has '$schema' I want to check if the next object in the array also has '$schema'. If it does then I want to label the current schema object, requestSchema and the next object will be called responseSchema. But if the next object does not contain '$schema' then the current object will be labeled responseSchema.

还有这个(来 self 对你的问题的评论):

Your question was a little unclear (I'd suggest proofreading it again and breaking up some of the run-on sentences). Are you saying that when you evaluate if ((lodash.has(res[key], '$schema')) && (lodash.has(res[key-1], '$schema'))) the value res[key-1] is always undefined?. So basically the 2nd if block never executes

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

 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 ] 动态访问它们。

我不知道你的代码到底有什么问题,但这至少会更具可读性,并且可能会阐明你的错误。

关于javascript - 循环遍历对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298857/

相关文章:

javascript - 点击时图像在上方移动 1px

javascript - 无法将点击事件绑定(bind)到回显元素

javascript - 如何在 JavaScript 中循环并将 JSON 对象放入数组中?

c - 在 C 中使用嵌套循环查找数组中的三个相同数字

Javascript:知道调用了哪个对象函数

javascript - 选择使用 javascript es5 更新或推送到数组

javascript - 如何从表格的不同行获取下拉列表的 id?

javascript - 在服务器端提交消息后关闭模态弹出窗口

c++ - 指向结构的指针怎么可能是数组呢?

javascript - 嵌套对象的键是否存储在对象中?