У меня есть массив объектов, называемых Рез и пытаюсь Переберите и организовывать объекты, основанные на том, один 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": [
"https://stackoverflow.com/questions/1"
]
},
"choices": {
"type": "array",
"items": [{
"type": "object",
"properties": {
"choice": {
"type": "string",
"enum": [
"Javascript"
]
},
"url": {
"type": "string",
"enum": [
"https://stackoverflow.com/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": "https://stackoverflow.com/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": [
"https://stackoverflow.com/questions/1"
]
},
"choices": {
"type": "array",
"items": [{
"type": "object",
"properties": {
"choice": {
"type": "string",
"enum": [
"Javascript"
]
},
"url": {
"type": "string",
"enum": [
"https://stackoverflow.com/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)
Ваш вопрос был немного неясным (я бы предложил исправить его снова и разбить некоторые предложения о запуске). Вы говорите, что когда вы оцениваете 'if ((lodash.has (res [key], '$ schema')) && (lodash.has (res [key-1], '$ schema')))' значение ' res [key-1] 'всегда не определено ?. Итак, в основном блок 2 * if * никогда не выполняется? – jusopi
@jusopi Да, это именно то, что я говорю. Я пытаюсь перейти к следующему или предыдущему объекту в массиве и проверить, имеет ли он «$ schema». Но я не уверен, почему то, что у меня есть, похоже, не делает трюк. –
Когда ключ = 0 k-1 = -1, который выходит за пределы. Аналогично, когда key = length -1 (последний элемент в массиве) key + 1 = length, которая выходит за пределы. Добавление, если проверка этих двух ситуаций должна устранить эту проблему. – nurdyguy