Get one object of array Json - javascript

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

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

Javascript print JSON Object

I want to parse this JSON array and print the salary so this what I have tried so far
there is nothing logged in the Console
if (data.action == 'SendArray') {
let invites = data.invites
const obj = JSON.parse(invites)
const myJSON = JSON.stringify(obj);
console.log(myJSON.salary)
}
JSON:
{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
{"factioname":"air-force", "inviter":"Admin","salary":8000}
This const myJSON = JSON.stringify(obj) turns your object back into a string, which you don't want.
I've done some setup to get your data matching your code but the two things you should note are:
Iterating through the array of invites using for .. of (you could use forEach instead) and
Using deconstruction to pull out the salary
data = { action: 'SendArray'
, invites: '[{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},{"factioname":"air-force", "inviter":"Admin","salary":8000}]'
}
if (data.action == 'SendArray') {
let invites = data.invites
const obj = JSON.parse(invites)
for ({salary} of JSON.parse(invites))
console.log(salary)}
myJSON is an array of objects. To log in console need to get each object. we can use forEach to get each object and then can console log the salary key.
let myJSON =[
{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
{"factioname":"air-force", "inviter":"Admin","salary":8000}];
myJSON.forEach(obj=> {
console.log(obj.salary);
});

fetch inner json object using javascript / node js

I am new to node and I am trying to fetch name from the obj but the problem is
How to fetch data from inner json object as my json object look like this
let obj=
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}
console.log(obj.h4354desdfqw.name)
I am trying to fetch all the name which are present inside the json object
like this
computer
Software
hardware
I am not sure in which representation you would like get the data. I can assume - you would like to get array of the names
let obj=
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}
const result = Object.values(obj).map(i => i.name);
console.log(result)
Object.values(obj).map(i => console.log(i.name));
You want to get the value of name for each object.
So let's iterate through each object's name with the map function :
const result = Object.values(obj).map(i => i.name);
console.log(result);

Map key of object with array of object value

Suppose I have an array of object as:
const bookDetails = [{"author":"john","email":"john#gmail.com","readingTime":"121"},
{"author":"romero","email":"romero#gmail.com","readingTime":908},
{"author":"romero","email":"alpha#gmail.com","readingTime":1212},
{"author":"buck","email":"buck#gmail.com","readingTime":1902},
{"author":"buck","email":"bujor#gmail.com","readingTime":12125},
{"author":"romero","email":"romero#gmail.com","readingTime":500},
{"author":"john","email":"john#gmail.com","readingTime":10},
{"author":"legend","email":"legend#gmail.com","readingTime":12}
{"author":"john","email":"john#gmail.com","readingTime":1890}]
I have an object as:
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
I want to replace emailId with corresponding author.
So my expected O/P should be: {"romero":1212,"john":1248,"buck":909}
If anyone needs any further information please let me know.
You can generate a new object by iterating over bookDetails and look up the values from toMatch
Like this
const bookDetails=[{"author":"john","email":"john#gmail.com","readingTime":"121"},{"author":"romero","email":"romero#gmail.com","readingTime":908},{"author":"romero","email":"alpha#gmail.com","readingTime":1212},{"author":"buck","email":"buck#gmail.com","readingTime":1902},{"author":"buck","email":"bujor#gmail.com","readingTime":12125},{"author":"romero","email":"romero#gmail.com","readingTime":500},{"author":"john","email":"john#gmail.com","readingTime":10},{"author":"legend","email":"legend#gmail.com","readingTime":12},{"author":"john","email":"john#gmail.com","readingTime":1890}]
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
const result = {};
for (const detail of bookDetails) {
const {email, author} = detail;
if (email in toMatch) {
result[author] = toMatch[email];
}
}
console.log(result);
Ah, you want to matching names from emails based on the array of objects. Is that right? If so..
const bookDetails=[{"author":"john","email":"john#gmail.com","readingTime":"121"},{"author":"romero","email":"romero#gmail.com","readingTime":908},{"author":"romero","email":"alpha#gmail.com","readingTime":1212},{"author":"buck","email":"buck#gmail.com","readingTime":1902},{"author":"buck","email":"bujor#gmail.com","readingTime":12125},{"author":"romero","email":"romero#gmail.com","readingTime":500},{"author":"john","email":"john#gmail.com","readingTime":10},{"author":"legend","email":"legend#gmail.com","readingTime":12},{"author":"john","email":"john#gmail.com","readingTime":1890}]
function namesMap(object,list){
//to save complexity(assuming the array is huge), I'd just loop through the list once to get the data I need
var obj={} //relates emails to names
list.forEach(item=>{
obj[item.email]=item.author
})
var toReturn={}
Object.keys(object).forEach(email=>{
toReturn[obj[email]]=object[email] //email to name conversion
})
return toReturn
}
//example usage
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
console.log(namesMap(toMatch,bookDetails))
There you go, I'm 100% you can do this easier, but this is the fastest response that came to my mind:
function changeData(bookDetails){
let returnableObject = {};
bookDetails.forEach(book => {
returnableObject[book.author] = book.readingTime
})
return returnableObject;
}
*EDIT -> This would work if your Author name IS UNIQUE if the author name is not unique you should change the name or maybe use an array of objects, not an object with multiple values...
*EDIT 2 -> I think I didnt understand your question.

Access specific data on Json - NodeJS

I'm trying to access data from a json but i can't... I have tried some explanations i found on the internet, but i guess there is something wrong on my code.
I'm getting data from a sql server database using the following code:
async function getLogin1(Operador, Senha) {
try {
let pool = await sql.connect(config);
let getLogin1 = await pool.request()
.input('input_parameter', sql.VarChar, Operador)
.input('input_parameter1', sql.VarChar, Senha)
.query("SELECT Codigo, Operador, Senha FROM Usuario where Operador = #input_parameter and Senha = #input_parameter1");
return getLogin1.recordsets;
}
catch (error) {
console.log(error);
}
}
So i get the recordsets here and put in a json:
router.route("/Login1").get((request, response) => {
console.log(request.body.operador);
console.log(request.body.senha);
Operador = request.body.operador;
Senha = request.body.senha;
dboperations.getLogin1(Operador, Senha).then(result => {
console.log(Operador, Senha);
response.json(result);
var json = JSON.stringify(result);
console.log(json);
})
})
On the console it shows the json:
[[{"Codigo":1,"Operador":"Username","Senha":"123456"}]]
I would like to get the individual data (codigo, operador and senha) to put in a individual string each one, but i cant access the data.
When I try like json[0] for example i get all the json (because my json has every info on the first position i guess), and when i try json.Codigo (for example) i get a "undefined" error.
What am i doing wrong and what the best way to solve?
And sorry for the low knowledge, this is my very first api.
(And yes, this is a login code and its not the best way to treat user data but its a very small system for intern use)
Your JSON "result" is:
[[{"Codigo":1,"Operador":"MASTER","Senha":"TERA0205"}]]
So it is an array of array containing one object with keys Codigo, Operador, Senha.
To get the value of the Codigo of that object you would likely need to
access it like
var CodigoVal = result[0][0].Codigo; // 1
var OperadorVal = result[0][0].Operador; // "MASTER"
Looks like json has nested array, if so json[0] will give inner array so you have to probably do like json[0][0].Codigo
[
[
{ "Codigo":1,
"Operador":"Username",
"Senha":"123456"
}
]
]
If we look at the JSON you posted above, we have an array which has an array with an object at its first index.
So to get access to that object you need to do:
const obj = json[0][0];
Now from obj you can extract Codigo, Operado and Senha like
const condigo = obg.Condigo;
const operado = obg.Operado;
const senha = obg.Senha;
You can also directly access them like
var codigo = json[0][0].Codigo;
var operador = json[0][0].Operador;
var senha = json[0][0].Senha;
json.Codigo doesnt work because your json has a array in it. Which has the object you are trying to get data from.
json[0] returns everything because that gives you the object from that array
so if you want Codigo try json[0][0].Codigo
I hope this helped you!

Json key and value in javascript

My Link json test file is the following:
[{"google" : "https://google.com"},{"bing" : "https://bing.com"}]
The javascript requesting the value, using axios:
var Links = './Links'
axios.get(Links)
.then(function(response){
console.log(response.data["google"]);
try {
var Test12 = JSON.stringify(response.data["google"]);
} catch (err) {
var Test12 = 'nothing'
}
The result is undefined.
My goal is to return the value of the input "google" or any input from the JSON and store it in the var as a string.
Since its an array of objects so you should access the values like,
response.data[0].google
OR
response.data[0]["google"]
Your data file is a list with two objects in it.
To access the google item you should access the list element.
var Test12 = JSON.stringify(response.data[0]["google"]);
Although I would change the json file to:
{"google" : "https://google.com", "bing" : "https://bing.com"}
Maybe like this:
var data=[{"google" : "https://google.com"},{"bing" : "https://bing.com"}];
data.forEach(function(el, index) {
Object.keys(el).forEach(function(val) {
console.log(val + " => " + el[val]);
});
});

Categories