Analyzing
In the question it is not clear what format your JSON document has for sure if it is really an array or if the tool you used to dump formatted the output of the data in an object.
Then I saw three possibilities for the format of your document:
1 . Being an object of objects
{"docs": {
"0": {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
"1": {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
"2": {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
"3": {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}}
}
2 . Being an object of an object array
{ "docs": [
{"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
{"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
{"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
{"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}]
}
3 . be simply an array of objects
[
{"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
{"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
{"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
{"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
]
As I could not determine the exact format of the document by the question I decided to create a function that analyzes the three possible formats and displays a report of the products contained in the document.
Developing
The function is called logElements(doc, root)
and accepts two strings as parameter doc
is a string in one of the three formats described above and root the document in the first two formats.
This function created to understand the problem is based on the question code and was made so that it can be easily reintegrated into the original code.
Its function is to extract an object from the JSON document, passed as parameter doc
, using the method JSON.parse(string)
and check if it is an array(third case), if it is not array it converts the object to an array using the method Object.values(obj)
the object identified byroot
as an array conversion target. The function ends by reporting using the correct method syntax Array.prototype.forEach(callback(currentValue)
.
// Objeto de objetos
var jsonCaso1 = `{ "docs": {
"0": {"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
"1": {"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
"2": {"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
"3": {"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
}}`;
// Objeto de uma array objetos
var jsonCaso2 = `{ "docs": [
{"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
{"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
{"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
{"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
]}`;
//Array de objetos
var jsonCaso3 = `[
{"_id": "produto-1", "descricao": "LANTERNA DIANT DIR", "referencia": "KADETTE"},
{"_id": "produto-10", "descricao": "HELICE", "referencia": "4044/46923"},
{"_id": "produto-100", "descricao": "BOMBA DE OLEO", "referencia": "BO0205/10055"},
{"_id": "produto-1000", "descricao": "CABO DO TRATOMETRO", "referencia": "229370"}
]`;
console.log("=".repeat(10) + "Teste JSON caso 1" + "=".repeat(10));
logElements(jsonCaso1 , "docs");
console.log("=".repeat(10) + "Teste JSON caso 2" + "=".repeat(10));
logElements(jsonCaso2 , "docs");
console.log("=".repeat(10) + "Teste JSON caso 3" + "=".repeat(10));
logElements(jsonCaso3);
function logElements(doc, root){
// Convert JSON para objeto
var obj = JSON.parse(doc);
if (obj === undefined){
console.log('Erro: Não foi possivel carregar os dados');
} else {
// Se o objeto convertido não for array converte o objeto cujo o nome ésta armazenado em root em array
if (!Array.isArray(obj)) obj = Object.values(obj[root]);
// Imprime o relatório, note a sintaxe de forEach se o objeto já é um Array é só usar direto.
obj.forEach(element => {
console.log("\nProduto = " + element._id + "\nDescrição = " + element.descricao + "\nReferência = " + element.referencia + "\n" + "-".repeat(40));
});
}
}
Answer
Applying the concepts used to create the function logElements
to your code and assuming that result
is a string in JSON format probably obtained from a Nosql DB:
this.localdb.find(req).then((result) => {
// Convert JSON para objeto
var result = JSON.parse(doc);
if (result === undefined) {
rej('Erro: Não foi possivel carregar os dados');
} else {
// Se o objeto convertido não for array converte o objeto
if (!Array.isArray(result )) result = Object.values(result["docs"]);
result.forEach(element => {
console.log(element);
});
res(result);
}
});
result.array
is null. Make a debug or useconsole.log(result)
to identify the variable value.– Valdeir Psr
I think the array in the foreach should be Capital no?!
– LeAndrade
Leandrade, I’ve done these tests before and the syntax is ok. But it’s not working. The question is how to extract this information. The result is being filled in, and if I display with the console.log(result) it displays json. My doubt is how I can extract this information because the structure is more or less like this: ːDocs: 0: {_id: "product-1", Description: "DIANT DIR FLASHLIGHT", Reference: "KADETTE"} }
– Gustavomgu.developer
You can’t tell exactly what the return type of the Api is, it’s an array of objects, this syntax
0: {...} 1: {...}
don’t know.– LeAndrade
@Gustavomgu.Veloper your question has two answers, we operate by a system of merits and punctuation. If any of the answer is useful and answers your question you could accept it. If you do not know how to accept an answer see our Tour.
– Augusto Vasques