How to return all objects of a JSON array

Asked

Viewed 1,407 times

1

I have an API that returns an array, containing values of the type:

[
    {
        "nome": "JOSE"
    },
    {
        "nome": "MARIA"
    },
    {
        "nome": "SERGIO"
    }
]

I need to return so I can display the information type: Name : Name :Maria Name :Sergio

How do I do it?

I’ve cracked my skull here, but I can’t find any way... Thank you!

Follow the code the way I’m trying to do, someone

const rp = require('request-promise');

function main(params) {
    // if (!params.name)
    // {
    //     return { message: 'Nome não encontrado.' };
    // }
    return rp({
        method: 'GET',
        uri: `URL AQUI`,
        json: true,
    })
    .then(body => {
        for (var i = 0; i < 10; i++) {//coloquei até 10 só pra testar
            var result = [];
            console.log(i);
            console.log(body.recordsets[0].length);
             console.log(body.recordset[i]);
             result.push(body.recordset[i]); // aqui eu tento colocar no array que criei em cima 
         }
        return result[0] ;
    })
    .catch(err => {
        return err;
    });
}

EDIT @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

COMING BACK JUST TO SAY THANK YOU:

Bom galera, muito obrigado pela ajudar, o code ficou assim:



<!-- language: lang-js -->

    const rp = require('request-promise');

    function main(params) {
        // if (!params.name)
        // {
        //     return { message: 'Nome não encontrado.' };
        // }
        return rp({
            method: 'GET',
            uri: `.....`,
            json: true,
        })
            .then(body => {
                var result = {'name' :[]};
                body.forEach((item) => {
                    Object.keys(item).forEach((propriedade) => {
                        result.name.push(item[propriedade])
                        console.log(propriedade, ' -> ', item[propriedade])
                    })
                })
               
                
                return result;
            })
            .catch(err => {
                return err;
            });
    }




<!-- end snippet -->

2 answers

1

Hello,

what you’re looking for is Object.Keys, it returns an array with the property of an object passed as parameter.

let nomes = [
  {
    "nome": "JOSE"
  },
  {
    "nome": "MARIA"
  },
  {
    "nome": "SERGIO"
  }
];

// para cada objeto, leremos as propriedades e printaremos no console.
nomes.forEach((item) => {
  Object.keys(item).forEach((propriedade) => {
    console.log(propriedade, ' -> ', item[propriedade])
  })  
})

will result in

nome  ->  JOSE
nome  ->  MARIA
nome  ->  SERGIO
  • Fantastic is this but my request only accepts that Return is a JSON obj and I have no idea how to do I thought of some output like: { "name": "JOSE","MARIA,"SERGIO" } this is possible?

  • @Emersonferreiravc need to return all the names together? this return of yours is an invalid json, can confirm how you need it?

  • Exactly, @h3nr1ke I need all the names together, I’m trying everything but I can’t, the structure is something like { "name": "JOSE","MARIA","SERGIO", ...} until there are no more items to add

  • to be valid would have to be something like {name: "Jose, Maria, Sergio"} or even {name: ["Jose", "maria", "Sergio"]}, which of these you search?

  • These are the processes related to your area: [{"name":"CON001 - CPF Query"},{"name":"AUX004 - Prevent Screen Lock"},{"name":"EMAIL002 - E-mail"},{"name":"EMAIL000 - POP3/SMTP"}] currently this is my answer and I wanted to make it more harmonious with only 1 field "name" and all the names inside it, you can understand me?

  • Not much =(, the structure you show is really very common and honestly do not see why to treat this return, in my view is already good, when make a loop to display where you need, I believe that has no problem, maybe rework this return is "complicate" your work. But going on, in my view, this structure is what you look for, so it would only have a field name and a simple array in it {name: ["Jose", "maria", "Sergio"]}, you could display all together using object.name.Join(',') for example and display all together

Show 1 more comment

1


To better understand how to do it, just first understand the structure (then the rest becomes easy).

What you have is an array, as it is enclosed by square brackets. In an array, the elements are between [ ] and separated by comma.

Within the array, each element is an object as it is bounded by keys. For example, { "nome": "JOSE" } is an object whose key "name" has the value "JOSE".

So in this array we have 3 elements, and each of them is an object with the key "name":

[ <-- início do array
    { "nome": "JOSE" },  <-- primeiro elemento do array
    { "nome": "MARIA" },  <-- segundo elemento do array
    { "nome": "SERGIO" }  <-- terceiro elemento do array
] <-- fim do array

To go through arrays, just use one for, and to access the key nome, just use her own name:

let nomes = [
    { "nome": "JOSE" },
    { "nome": "MARIA" },
    { "nome": "SERGIO" }
];

for (const obj of nomes) { // para cada elemento do array, imprime o nome
    console.log(`Nome=${obj.nome}`);
}

The exit is:

Nome=JOSE
Nome=MARIA
Nome=SERGIO

Like you said that wants to "merge" the names into a single structure, one option is to put all the names into a single array:

let nomes = [
    { "nome": "JOSE" },
    { "nome": "MARIA" },
    { "nome": "SERGIO" }
];

let result = { 'nomes': [] }; // começa com um array vazio: []
for (const obj of nomes) { // adiciona os nomes no array acima
    result.nomes.push(obj.nome);
}
console.log(result); // { nomes: [ 'JOSE', 'MARIA', 'SERGIO' ] }

// outra opção é usar map:
result = { 'nomes': nomes.map(obj => obj.nome) };
console.log(result); // { nomes: [ 'JOSE', 'MARIA', 'SERGIO' ] }

Thus, the result is an object with the key "names", whose value is an array containing all the names of the original array.


The solution of another answer is more general if the objects have more than one key. But if the idea is to take only the "name" key, just access it directly.

  • 1

    Exactly that, I get by doing a gambit here, but I will definitely alter and do it right

Browser other questions tagged

You are not signed in. Login or sign up in order to post.