How to access elements of json in Angular 2 - json

when I did
loadPeople(){
this.myService.load().then(data => {
this.people = data;
alert(this.people);
});
}
it alerts json as :
{
"status": "true",
"statusCode": 200,
"response": [{
"user_id": "92",
"firstname": "joy",
"lastname": "Panchal",
"email": "joy#gmail.com",
"password": "7Y7+K0vZIVWPDUQH++Iu+/+tMZ",
"user_type_id": "1"
}, {
"user_id": "89",
"firstname": "mark",
"lastname": "haris",
"email": "mark#gmail.com",
"password": "4JICqnTkR8ysTI+nQQ+rpfAf7e",
"user_type_id": "1"
}]
}
now i am trying to access "response" by
loadPeople(){
this.myService.load().then(data => {
this.people = data.response;
alert(this.people);
});
}
but it alerts as "undefined" .
can anyone tell where i am missing ??

you can access like this. please try.
`loadPeople(){
this.myService.load().then(data => {
this.people = JSON.parse(data.response);
alert(this.people);
});
}`

you need parse JSON first:
this.myService.load().then(data => {
let res = JSON.parse(data);
this.people = res.response;
alert(this.people);
});
}

Related

Sequelize Insert Cascade

im trying insert in multiple tables.
let me explain User create a new client, client insert id into bill - (idClient) table
this is the payload
{
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"services": [1, 2, 3],
"bill":{
"description": "New project"
}
}
the insert
_service.create = async (client) => {
const { description } = client.bill;
try {
const data = await Client.create(
{ client, bill: { description: description } },
{ include: { model: Bill } }
);
return data.id;
} catch (err) {
handleError = err.hasOwnProperty("errors")
? err.errors.map((error) => error.message)
: err;
throw new Error(handleError);
}
};
but im getting this error
{
"name": "Error",
"message": "ReferenceError: description is not defined"
}
and yes, bill table has that column.
the relation
Client.hasOne(models.Bill, { foreignKey: "idClient" });
so, im stuck, i read the documentation and i trying to do the same way as they do but i dont know what i doing wrong
https://sequelize.org/master/manual/creating-with-associations.html
I already did, i dont know if the best way
i modified the payload
{
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"description": "new Proyect",
}
the insert query, change bill to Bill as my table name and then add description value
const { description } = client;
const data = await Client.create(
{ ...client, Bill: { description } },
{ include: { model: Bill } }
);
and the result
{
"id": 6,
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z",
"Bill": {
"id": 4,
"idClient": 6,
"totalAmount": null,
"description": "new Proyect",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z"
}
}

How to extract only certain properties of json, returning as an observable using rxjs

For example this is the json which I am receiving,
{
"events": [...
],
"total": 12341,
"students": [
{
"id": 1,
"first_name": "John",
"last_name": "Apple"
},
{
"id": 2,
"first_name": "Bob",
"last_name": "Banana"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Carrot"
}
]
}
And I want to transform the data to the following form, and return it as an observable
[
{
"first_name": "John",
"last_name": "Apple"
},
{
"first_name": "Bob",
"last_name": "Banana"
},
{
"first_name": "Charles",
"last_name": "Carrot"
}
]
I have tried the following, but it returns undefined.
getStudentsName(): Observable<any> {
const requestUrl = this.rootURL + `students/`;
let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));
return studentsInfo.pipe(map(students => {students.first_name, students.last_name}));
}
returns undefined when subscribing to observable
this.getStudentsInfoService.getStudentsName()
.subscribe((result) => console.log('here', result));
It looks like it can't find students. Try this :
return studentsInfo.pipe(map(s => { return {
first_name: s.first_name,
last_name: s.last_name,
}}));
Your problem is, that students is an array, but you handle it as an object. You need to add a nested map: 1 for rxjs, 1 for the array
return studentsInfo.pipe(
map(studentsArray => studentsArray.map(student => ({
first_name: student.first_name,
last_name: student.last_name
}))),
);
PS.: Using types instead of any would have shown you that. Neither you nor the other responders saw this issue due to missing typing.
Here is a short code snippet.
const object = {
"total": 12341,
"students": [
{
"id": 1,
"first_name": "John",
"last_name": "Apple"
},
{
"id": 2,
"first_name": "Bob",
"last_name": "Banana"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Carrot"
}
]
}
let arr: any = [];
object.students.forEach(person => arr.push(
{
"first_name": person.first_name,
"last_name": person.last_name
}))
console.log(arr)
[LOG]: [{ "first_name": "John", "last_name": "Apple" },
{ "first_name": "Bob", "last_name": "Banana" }, { "first_name": "Charles", "last_name": "Carrot" }]
You can iterate over students with a foreach loop and then create a new json which you then push in your new array
this.http.get<any>(requestUrl).pipe(map(o => o.students.foreach(person => arr.push({
...}));
The Problem
The Problem is with your how you return your observable
Lets break the code down
let studentsInfo = this.http.get<any>(requestUrl).pipe(map(o => o.students));
In the above studentsInfo will be of type Observable<any>
Next line is as per below
return studentsInfo.pipe(
map(students => {
students.first_name, students.last_name
}
));
Lets have a look at the below section
{
students.first_name, students.last_name
}
This part of the section actually has no return statement hence by default javascript returns undefined!
Solution
To use arrow function without a return statement, you will need to wrap {} inside a () like below
students => ({ })
Below will work
getStudentsName(): Observable<any> {
return this.http.get<any[]>(`${this.routeURL}/students`).pipe(
map(o => o.students));
}

Mapping data that contains dots in React

I am trying to map the data in React that is coming from the API but I am having problems mapping the object that contains dots for example this: name.en_US.
What is the proper way to map this object and keeping the data structure that I have?
I am getting the date in this format from the API:
{
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
},
And then I am trying to map it using the following code.
const {
user,
employeeId,
businessCustomer,
endCustomer,
device,
task
} = task;
const{
endCustomerName,
address,
place
} = endCustomer;
const {
shipmentIds,
names
} = device;
const{
en_US,
fi_FI
} = names;
const {
time,
duration,
summa
} = task;
const data = {
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
};
const { device } = data;
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
const nameUS = device['name.en_US'];
console.log(name_en_US, nameUS);
Use [ ] notation like, device['name.en_US'] .
You can destructure your propery as #Vishnu mentioned, or you could also destructure it by providing a valid key name
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
And then you could access your variable with name_en_US.

Fetch JSONFile Reponse in angular

I have one json file which contains multiple objects inside another object,I want to iterate there key and values in my HTML Page:
Exemple :
{
"firstName": "Ayoub",
"lastName": "Gammar",
"mntDc": 502.0,
"childs": [
{
"firstName": "Rafik",
"lastName": "Mansour",
"mntDc": 500.0,
"username": "user3"
},
{
"firstName": "Ahmed",
"lastName": "Makni",
"mntDc": 1.0,
"childs": [
{
"firstName": "ALi",
"lastName": "hama",
"mntDc": 500.0,
"username": "admin"
}
],
"username": "user2"
}
],
"username": "user1"
}
Angular Methode :
this.usrerArbre.getArbre().subscribe(data=>{
console.log('data'+data);
this.arbreUSer=data;;
},error1 => {
console.log(error1)
})
}```
I don't understand which key you want to iterate. If you want to iterate the childs key then you can iterate it like this:
(data.childs||[]).forEach((item, index) {
console.log(item, index);
});
But if you want to iterate the whole object then you can get its keys from:
let keys = Object.keys(data);
(keys||[]).forEach(function(item, index) {
console.log(data[item], index); // You will get the each object key value here
});
Try this,
this.usrerArbre.getArbre().subscribe(data=>{
console.log('data'+data);
this.arbreUSer=data.childs;
},error1 => {
console.log(error1)
})
}
.html
<div *ngFor="let data of arbreUSer">
<p>{{data.firstName}}</p>
<p>{{data.lastName}}</p>
<p>{{data.mntDc}}</p>
<p>{{data.userName}}</p>
</div>
Here is a short solution:
var result = Object.entries(data).map(([key, value]) => ({key,value}));
//console.log(result);

How to control keys to show in Json Object

I am using following NodeJs code to get the JsonObject:
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index];
}
res.send(resp);
});
Getting output :
{
"emp1": {
"cas": {
"0": 637861888,
"1": 967242753
},
"flags": 0,
"value": {
"eid": "10",
"ename": "ameen",
"gender": "male",
"designation": "manager",
"country": "Singapur",
"reportee": "Suresh",
"salary": 50000,
"picture": "ameen.jpg"
}
},
"emp2": {
"cas": {
"0": 721747968,
"1": 430939000
},
"flags": 0,
"value": {
"eid": "2",
"ename": "shanmugapriya",
"gender": "female",
"designation": "programmer",
"country": "England",
"reportee": "shruti",
"salary": 14250,
"picture": "priya.jpg"
}
}
}
What I want to do is, I want to display only value key. Can anybody help me how to do this.
Thanks in advance.
Do you mean you want to display only value and key? If so the code below will put only value into the result
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index].value;
}
res.send(resp);
});
The result response will be
{
"emp1":{
"eid":"10",
"ename":"ameen",
"gender":"male",
"designation":"manager",
"country":"Singapur",
"reportee":"Suresh",
"salary":50000,
"picture":"ameen.jpg"
},
"emp2":{
"eid":"2",
"ename":"shanmugapriya",
"gender":"female",
"designation":"programmer",
"country":"England",
"reportee":"shruti",
"salary":14250,
"picture":"priya.jpg"
}
}
UPDATE: Your question was really ambiguous. I think you would need to use Couchbase Views here. Docs http://docs.couchbase.com/couchbase-sdk-node-1.2/#querying-a-view. Assuming that you will build the view _design/employees/_view/all with the following map function:
function(doc, meta) {
emit(meta.id, doc);
}
Your node.js code will look like this
var view = bucket.view('employees', 'all');
view.query(function(err, results) {
res.send(results);
});