I have the following JSON-encoded data being returned and need to process it with jQuery.
How can I access different depots and vehicle data inside this list using jQuery.getJSON()'s callback function?
$.getJSON('url', function(data) {
// ...?
});
The JSON-encoded data:
// top-level result is a list of dictionaries
[
// return dictionary for each depot
{
depot: {
_id: 'D3',
intersection: {
first: 'Bay',
second: 'King'
},
address: {
number: '100',
street: 'King street West',
city: 'Toronto',
province: 'ON',
postal_code: 'M5X 1B8'
},
},
// return dictionary for each car in that depot
vehicle: [{
_id: 'V4',
_depot_id: 'D3',
model: 'Ford F150',
price: '80',
km_per_litre: '15',
cargo_cu_m: 'YES',
category: 'Truck',
image: 'www.coolcarz.com'
}, {
_id: 'V24',
_depot_id: 'D3',
model: 'Toyota Camry Hybrid',
price: '90',
km_per_litre: '25',
cargo_cu_m: 'YES',
category: 'Hybrid car',
image: 'www.coolcarz.com'
}
]
},
{
depot: {
_id: 'D9',
intersection: {
first: 'Bay',
second: 'Front'
},
address: {
number: '161',
street: 'Bay',
city: 'Toronto',
province: 'ON',
postal_code: 'M5J 2S1'
},
},
// return dictionary for each car in that depot
vehicle: [{
_id: 'V11',
_depot_id: 'D9',
model: 'Ford Crown Victoria',
price: '45',
km_per_litre: '13',
cargo_cu_m: 'YES',
category: 'Standard car',
image: 'www.coolcarz.com'
},
]
},
]
$.getJSON('url', function(data) {
alert(data.length); // 2
alert(data[0].depot.intersection.second); // "King"
alert(data[0].vehicle[1].category); // "Hybrid car"
alert(data[1].depot.address.city); // "Toronto"
});
Related
Need help on a problem with Rxjs join.
I have two observables with common id, I want to perform join to show records
from both objects based on id.
let emp = of([
{ id: 1, name: 'aa', age: 20 },
{ id: 2, name: 'bb', age: 21 },
{ id: 3, name: 'cc', age: 22 },
{ id: 4, name: 'dd', age: 23 }
]);
let details = of([
{ id: 1, address: 'ee' },
{ id: 1, address: 'ff' },
{ id: 2, address: 'gg' },
{ id: 2, address: 'hh' }
]);
I need the join like this:
[
{id: 1, name: 'aa', age: 20, details: [{address: 'ee'},{address: 'ff'}] },
{id: 2, name: 'bb', age: 21, details: [{address: 'gg'},{address: 'hh'}] },
{id: 3, name: 'cc', age: 22, details: undefined },
{id: 4, name: 'dd', age: 23, details: undefined },
]
I have tried like this:
forkJoin([emp, details]).pipe(
map(([_emp, _details]) =>
_emp.map((item) => {
return ( {
...item,
details: _details.find((item1) => {
return item1.id === item.id
})
})
})
)
).subscribe(console.log)
I got the result:
[
{id: 1, name: 'aa', age: 20, details: [{address: 'ee'}] }, // {address: 'ff'} missing
{id: 2, name: 'bb', age: 21, details: [{address: 'gg'}] }, // {address: 'hh'} missing
{id: 3, name: 'cc', age: 22, details: undefined },
{id: 4, name: 'dd', age: 23, details: undefined },
]
In this result second address is missing for id 1 and 2.
Instead of [{address: 'ee'},{address: 'ff'}], I got only first match [{address: 'ee'}] for id 1.
Instead of [{address: 'gg'},{address: 'hh'}], I got only first match [{address: 'gg'}] for id 2.
Please help me to accomplish the desired result
I think you should use filter() instead of find(). The find() operator returns only the first match.
forkJoin([emp, details]).pipe(
map(([_emp, _details]) =>
_emp.map((item) => {
return ({
...item,
// This is the line you have to modify:
details: _details.filter((item1) => item1.id === item.id)
})
})
)
).subscribe(console.log)
I have a service function to get users from my MySQL database using Sequelize ORM and i would to like to append fullName to the Users.
const filterUsers = async ([...users]:IUsers[]) => {
let searchAttributes = {};
if (users) { searchAttributes = { [Op.or]: users }; }
const filteredUsers = await User.findAll({
raw: true,
nest: true,
where: { ...searchAttributes },
include: [{
model: Club,
as: 'homeClub',
}, {
model: Club,
as: 'awayClub',
}] });
return filteredUsers as unknown as IUsersWithTeams[];
};
FilteredUsers response:
filteredUsers =
[
{
id: 1
name: 'John',
LastName: 'Mayer',
homeClub: 'Barcelona',
awayClub: 'Real Madrid',
},
{
id: 2,
name: 'Adam',
LastName: 'Smith',
homeClub: 'PSG',
awayClub: 'Milan',
},
]
What i would like to receive:
const expectedUserResponse = [
{
id: 1
name: 'John',
LastName: 'Mayer',
FullName: 'John Mayer',
homeClub: 'Barcelona',
awayClub: 'Real Madrid',
},
{
id: 2,
name: 'Adam',
LastName: 'Smith',
FullName: 'Adam Smith',
homeClub: 'PSG',
awayClub: 'Milan',
},
]
How can i do that ? Thank you very much if you can help me ;)
You need to use a virtual field, see documentation and my other answer to the similar question. It seems the official documentation has the example that perfectly fits your request:
const { DataTypes } = require('#sequelize/core');
const User = sequelize.define('user', {
firstName: DataTypes.TEXT,
lastName: DataTypes.TEXT,
fullName: {
type: DataTypes.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('Do not try to set the `fullName` value!');
}
}
});
Actually im new to mongoDB and mongoose, and im tryig to get nested join using three schemas and grouping them.
const company = Schema(
{
title: {type: String, required: true},
}
);
const plans = Schema(
{
companyId: {type: Schema.Types.ObjectId, ref: 'company', required: true},
title: {type: String, required: true},
}
);
const promotions = Schema(
{
planId: {type: Schema.Types.ObjectId, ref: 'plans', required: true},
title: {type: String, required: true},
}
);
I got the below result but separated, and I would like to group it, any help with this point would be appreciated?
[
{
_id: '621c2749ac447abf20a8a263',
title: 'test 1',
plans: {
_id: '621c290ad6bce1084f900b0b',
title: 'test 1',
promotions: {
_id: '621d1187b18de3c35fa3963b',
title: 'test 1',
},
},
},
{
_id: '621c2749ac447abf20a8a263',
title: 'test 2',
plans: {
_id: '621c290ad6bce1084f900b0b',
title: 'test 2',
promotions: {
_id: '621d1187b18de3c35fa3963d',
title: 'test 2',
},
},
},
];
The result that i want to achieve is:
[
{
title: 'company name',
plans: [
{
title:'plan name',
promotions: [
{
title:'promotion name'
}
]
},
...
]
},
...
]
A nested "$lookup" is one way to do it.
db.company.aggregate([
{
// lookup plans matching companies
"$lookup": {
"from": "plans",
"localField": "_id",
"foreignField": "companyId",
"pipeline": [
{
// lookup promotions matching plans
"$lookup": {
"from": "promotions",
"localField": "_id",
"foreignField": "planId",
"as": "promotions"
}
}
],
"as": "plans"
}
},
{
// drop unwanted fields
"$project": {
"_id": 0,
"plans._id": 0,
"plans.companyId": 0,
"plans.promotions._id": 0,
"plans.promotions.planId": 0
}
}
])
Try it on mongoplayground.net.
Update: I am trying to do subtract expression in JSON file.
export const PRODUCTS: Products[] = [
{
id: 1,
productCat:'Product Cat',
product: [
{
productName: 'Product Name',
newPrice: 800,
oldPrice: 1000,
save: 'oldPrice' - 'newPrice'
},
],
}
]
I am new to JSON so I dont know if it's even possible. If there is any other way please help.
Use forEach function to add save key. like this
const PRODUCTS = [{
id: 1,
productCat: 'Product Cat',
product: [{
productName: 'Product Name',
newPrice: 800,
oldPrice: 1000
},
{
name: 'Product Name 2',
newPrice: 1800,
oldPrice: 10000
}
],
}];
PRODUCTS[0].product.forEach(itm => itm['save'] = itm['oldPrice'] - itm['newPrice']);
console.log(PRODUCTS);
export default [
{
user:{
id: '1',
person: 'Theodore Roosevelt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
},
{
user:{
id: '2',
person: 'Normale',
text: 'Change your thoughts and you change your world.',
icon:'woman'
}
}, {
user:{
id: '3',
person: 'Thlt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
}]
The code above is a ts file under data folder in ionic tool.
I wish to delete an entry from this array on basis of id by click of delete button in front of each entry.
I'm new to ionic . I tried .slice it didn't work
const arr = [{
user:{
id: '1',
person: 'Theodore Roosevelt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
},
{
user:{
id: '2',
person: 'Normale',
text: 'Change your thoughts and you change your world.',
icon:'woman'
}
}, {
user:{
id: '3',
person: 'Thlt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
}]
const id = '2'; // 2 will be removed
const result = arr.filter(item => (item.user || {}).id !== id)
console.log(result)