How to read objects and store into array - arrays

I made an http request and got back e.g the below json. I want to read the cars and the shoes objects into separate arrays at the time of the http request.
json
{
"id": 9,
"name": "Zlatan",
"cars": [
{
"type": "ford",
"year": "2019"
},
{
"type": "audi",
"year": "2017"
}
]
"shoes": [
{
"brand": "adidas",
"status": "old"
},
{
"brand": "timberland",
"status": "new"
}
]
}
comp.ts
cars = [];
shoes = [];
//......
getZlatan() {
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars ....//what to add here
this.shoes ....// here too.
} );
}
Or is there a cleaner way to load the arrays at http request?

Access the cars and shoes properties of the data with simple dot-notation. It might be ideal to check if the data returned is not null with if(condition here) and then perform your logic. If you have more objects and want to bring all cars and shoes under one array then you have to loop through.
getZlatan() {
return this.httpService.getInfo()
.subscribe(data => {
this.objZlatan = data;
this.cars = this.objZlatan.cars;
this.shoes = this.objZlatan.shoes;
});
}

Just use . and type names to access cars and shoes. Let me show an example:
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars = data.cars;
this.shoes =data.shoes;
} );

Related

Problem with left join with contition typeorm

This is my code:
const query = this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
);
And this is data I got from query:
"requests":
[
{
"id": "8ceee413-521c-4e21-a75b-27048d184804",
"status": "waiting",
"reason": "1",
"approvers": [
{
"id": "04946109-ba35-4c08-a469-761023f33b3c",
"employeeCode": "EMP001",
"status": "waiting",
},
{
"id": "a9dec055-e237-434c-897e-d877f64df4af",
"employeeCode": "EMP002",
"status": "approved",
}
]
}
]
The problem is that when I add contidion to get all request which have been approve by employee EMP002
query.andWhere(`approvers.employeeCode = 'EMP002'`)
The approvers[0] is missing. I know that's correct but I wonder if there is a way to get full approvers but still get requests which have EMP002 is a approver. Thank you for your attention.
You can do this using two queries. First, get all the ids of the request where approvers.employeeCode = 'EMP002'. Then get all the requests where id of request equals the requestIds fetched above.
const results = await this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
)
.select('request.id', 'id')
.where('approvers.employeeCode = :empCode', { empCode: 'EMP002' })
.getRawMany();
const requestIds = results.map(e => e.id);
const requests = await this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
)
.where('request.id IN (:...requestIds)', { requestIds: requestIds });
requests would now contain the desired result.

how to make slots output different responses

Doing some smart home skill development and my Intent utterance is "how long until my battery is {state}" State being either empty or full. I know I could do this with different intents but I wont want to have two many intents as I already have many. I basically want the user to say either full or empty in place of {state}. and then from there, depending on their answer, give different answers for full or empty. I haven't found much online so i hope you guys can help. Im also new to code.
You should create a slot for your battery state:
{
"name": "BatteryState",
"values": [
{
"id": "empty",
"name": {
"value": "empty"
}
},
{
"id": "full",
"name": {
"value": "full"
}
}
]
}
You can create it by yourself in the UI or paste in types collection in JSON editor.
Then use created slot in your intent
{
"name": "BatteryStateIntent",
"slots": [
{
"name": "batteryState",
"type": "BatteryState"
}
],
"samples": [
"how long until my battery is {batteryState}"
]
}
You can create it by yourself in the UI or paste in intents collection in JSON editor.
Then in the code:
const BatteryStateIntentHandler = {
canHandle(handlerInput) {
return (
Alexa.getRequestType(handlerInput.requestEnvelope) === "IntentRequest" &&
Alexa.getIntentName(handlerInput.requestEnvelope) === "BatteryStateIntent"
);
},
handle(handlerInput) {
const batteryStatus =
handlerInput.requestEnvelope.request.intent.slots.batteryState.value;
let speakOutput = "";
if (batteryStatus === "full") {
const timeToFull = 10; // or some sophisticated calculations ;)
speakOutput += `Your battery will be full in ${timeToFull} minutes!`;
} else if (batteryStatus === "empty") {
const timeToEmpty = 5; // or some sophisticated calculations ;)
speakOutput += `Your battery will be full in ${timeToEmpty} minutes!`;
} else {
speakOutput += "I don't know this status";
}
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
},
};
Make sure you used the same intent name as in the builder. And at the end, add created intent handler to request handlers:
exports.handler = Alexa.SkillBuilders.custom()
.addRequestHandlers(
BatteryStateIntentHandler,
// ...
)
.lambda();

Converting a typescript class object with dictionary to a JSON array

After some digging I decided my backend needed to consume duplicate keys and as a consequence my frontend can no longer send a dictionary as a JSON string.
See my previous question.
After applying the solution provided
let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json' }
let jsonObject = {};
for (let entry of mediatagRequest.tags.entries())
{
jsonObject[entry[0]] = entry[1];
}
const body = JSON.stringify({
tags: jsonObject
});
My current output (which is what I then wanted)
{
"tags": {
"city": "Karachi"
}
However my needs have changed and after a bit of of struggle I couldn't get my desired output to be like this
{
"tags": [
{
"key": "city",
"value": "Karachi"
},
{
"key": "city",
"value": "Mumbai"
}
]
}
Could someone help, thank you.
To get your desired output you could use the Object.entries() function to get the key, value pairs separately. This code segment will turn an object into a list of objects with key value pairs:
test_object = {
karachi: "dubai",
mumbao: "moscow",
};
output = Object.entries(test_object).map(([key, value]) => ({ key, value}));
console.log(output);
You can adapt this code to select the desired parts of your object and format them as you like. There are other Object functions you can see in the documentation.

convert JSON data into table based on elements seperated by \n for header elements and \t for table elements using angularJS

"results": {
"code": "SUCCESS",
"msg": [
{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}
]
},
this is my example code,where ever we have \n consider as header elements of table and \t consider as tr elements,can you provide me any suggestion.
You might be looking something like this. In your HTML code right one ng repeat for head and other for each row of the table.
var result = {
"code": "SUCCESS",
"msg": [{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}]
}
var format = result.msg.map((r) => {
var str = r.data;
var arr = str.split('\n');
var head = arr.splice(0, 1)[0].split('\t');
arr.pop(); // remove empty string
var data = arr.map((d) => {
return d.split('\t').reduce((obj, x, index) => {
obj[head[index]] = x;
return obj;
}, {})
})
return {
head,
data
}
});
console.log(format);

How to do a get request with all idRefs

I have 2 models in my project, 1 is stores and the other is products, the stores has a reference to products like this:
produtos: [
{ type: mongoose.Schema.ObjectId, ref: 'Produto' }
]
and basicly at the moment i have a object like this:
{
"_id": "589715a3a2030f7bc143ed89",
"nome": "levis2",
"email": "filipecostaa10#gmail.com1",
"password": "1234",
"__v": 8,
"produtos": [
"58971695a2030f7bc143ed8a",
"589716d7a2030f7bc143ed8b",
"58971742a2030f7bc143ed8c",
"58971770a2030f7bc143ed8d",
"589717a1a2030f7bc143ed8e",
"58971848a2030f7bc143ed8f",
"589718f5a2030f7bc143ed90",
"58971937a2030f7bc143ed91"
],
"descricao": "No description for this store"
}
the array produtos has a lot of ids. Those ids are reference to the products; What i need to know now is how i can do a get request to get all the products with those ids, how do i send the request?
here is my router
router.get('/',function(req,res){
Loja.find(function(err,lojas){
if(!lojas){
return res.status(404).json({Error:"Loja nao encontrada"});
}
res.send(lojas);
}).populate("Produto");
})
Seems you are trying to get all stores with populated products field so:
router
.route('/')
.get(function(req, res) {
Loja
.find()
.populate('produtos')
.exec(function(err, lojas) {
if ( err ) {
return handleError(err);
}
res.json(lojas);
});
});

Resources