Get one object of array Json

Viewed 53

I followed this little how to to apply a simple api in nodejs. It is not quite my area of ​​expertise, I am a Computer Network Analyst and although I develop applications in C ++ (simple) and C #, I have a small doubt on how to obtain the result of an array returned by the following code:

Javascript Code using Mysql ->

//
 exports.findAll = (req, res) => {
 const name = req.query.name;
 var condition = name ? { name: { [Op.like]: `%${name}%` } } : null;

Custumers.findAll({ where: condition })
.then(data => {
    res.send(data);;
})
.catch(err => {
  res.status(500).send({
    message:


      err.message || "Some error occurred while retrieving name."
   });
 });
};

Access to URL to check if everything goes as expected.

http://10.1.1.254:8085/api/custumers?name=Gabriel

My result:

  [
   {"id":6,
   "name":"Gabriel",
   "cod":10,
   "igCustumer":"1",
   "createdAt":null,
   "updatedAt":null}
   ]

How could I get the values ​​of name, cod, imgCustumer?

Im try;

axios.get(`http://10.1.1.254:8085/api/custumers?name=Gabriel`).then((res) => {
let myvar = `My result:\n\n${res.data.name}`;
console.log(myvar);
})

Result if : Undefinid

4 Answers

You can access object values in JavaScript like this...

let res =   [{"id":6,
   "name":"Gabriel",
   "cod":10,
   "igCustumer":"1",
   "createdAt":null,
   "updatedAt":null}]

let name = res[0].name;
let cod = res[0].cod;
let igCustomer = res[0].igCustumer;

Because res is an array full of objects, you access an object with its location in the index, like res[0]. From there you can select the key/value pair in your object by using dot notation or brackets. Each method has its use.

Try something like this:

let res = [
   {"id":6,
   "name":"Gabriel",
   "cod":10,
   "igCustumer":"1",
   "createdAt":null,
   "updatedAt":null}
   ]

console.log(res[0]['name']);
console.log(res[0]['cod']);
console.log(res[0]['igCustumer']);

The problem with your code that you are trying to access a field that does not exists. The res.data will be equal to the response of your endpoint. Your response is an array, so apparently it does not have name field. So you need to take a particular object.

const user = res.data[0]; // Taking the first user.

Then you can access its data.

user.name; // Gabriel

To find data from array, you can iterate that array and use find like this :

let res = [
   {id:6,
   name:"Gabriel",
   cod:10,
   igCustumer:"1",
   createdAt:null,
   updatedAt:null}
   ]

let myVar = res.find((item) => {
  return item.name === 'Gabriel'
});

console.log(myVar.name);
console.log(myVar.cod);
console.log(myVar.igCustumer);

Related