Filtering a json array based on a list of values - json

I am new to typescript in angular 2 and i stuck with a situation.
I have a json array in this format
needle json
[{"empId":100,"orgId":500}
{"empId":201,"orgId":566}]
The above json is in a particular order and we need to keep that order maintained while looking for those in another json array(Haystack)
Haystack json array
[
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
]
Now i need to get those values from haystack array whose id matches in needle keeping the order maintained of the needle
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"}
I have achieved the solution to this problem but i guess my solution is not optimal as i am using many loops. Can some one suggest me a good solution.
PLS NOTE: Order of the employee id should be maintained in result json as of the needle json.
Thanks a lot :)

This should work
public needle: any;
public hayStack: any;
this.needle = [
{"empId": 100, "orgId": 500},
{"empId": 201, "orgId": 566}
];
this.hayStack = [
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
];
const needleEmpId = this.needle.map(item => item.empId);
const hayStackEmpCode = this.hayStack.map(item => item.empCode);
const result = hayStackEmpCode.map((id, index) => {
if (needleEmpId.indexOf(id) != -1) {
return this.hayStack[index];
}
}).sort().filter(item => (item != undefined));
console.log(result);
Result
0:{empCode: 100, fname: "Alex", Lname: "Mishra"}
1:{empCode: 201, fname: "Rick", Lname: "Mandez"}

Related

DART - Filter JSON Data

I'm trying to filter the json data. There is a field called "brand" in my json (so basically I'm trying to filter the data by brands)
This is how my json looks
{
"items": [
{
"_id": "30baa1ca-4186-4ff0-abe8-a5970e753444",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-09T08:47:29.137Z",
"discountedPrice": "44.97",
"_updatedDate": "2022-05-09T08:48:44.147Z",
"getDealLink": "https://amzn.to/3FqBq4O",
"brands": [
"Amazon"
],
"title": "Mellanni Extra Deep Pocket Twin XL Sheet Set ",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"save": "#1 Best Seller",
"link-items-all": "/items/",
"link-items-title": "/items/mellanni-extra-deep-pocket-twin-xl-sheet-set-"
},
{
"_id": "a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3",
"_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
"_createdDate": "2022-05-08T22:35:38.398Z",
"discountedPrice": "$81.59",
"_updatedDate": "2022-05-08T22:39:52.801Z",
"getDealLink": "https://amzn.to/3ymXGLe",
"brands": [
"Amazon"
],
"originalPrice": "$199.99",
"title": "2 Pack Stadium chairs for bleachers with back support",
"amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
"link-items-all": "/items/",
"link-items-title": "/items/2-pack-stadium-chairs-for-bleachers-with-back-support"
},
and this is my dart code
void getAmazon() async {
var response = await http.get(Uri.parse(url));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
print(filteredData); // returns nothing
}
it doesn't return/print anything. What am I doing wrong?
Better to use contains to check if a brand is listed. Also check if "brands" field is available for better stability.
final filteredData = data.where((element) => (element['brands'] != null ? element['brands'].contains('Amazon') : false));
In your code, you are checking if brands it's equal to Amazon, but brands is actually a List. (Or in the case you are checking on a particular index, this could change)
So ["Amazon"] ≠ Amazon.
In the code below you will now check if brands contains "Amazon".
Iterable filteredData = data.where((element) => element['brands'].contains('Amazon'));
void getAmazon() async {
var response = await http.get(Uri.parse('https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e'));
var decodeResponse = jsonDecode(response.body);
List data = decodeResponse['items'] as List;
Iterable filteredData = data.where((element) => element['brands'][0] == 'Amazon');
log('ddf ${filteredData}'); // returns nothing
}
I had added third product as brand from flipkart it filter this!
you can check this url https://mockbin.org/bin/e123b53d-6e35-49e7-a94e-f49554a63d7e
Your code actually works as expected!!!
[log] ddf ({_id: 30baa1ca-4186-4ff0-abe8-a5970e753444, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-09T08:47:29.137Z, discountedPrice: 44.97, _updatedDate: 2022-05-09T08:48:44.147Z, getDealLink: https://amzn.to/3FqBq4O, brands: [Amazon], title: Mellanni Extra Deep Pocket Twin XL Sheet Set , amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, save: #1 Best Seller, link-items-all: /items/, link-items-title: /items/mellanni-extra-deep-pocket-twin-xl-sheet-set-}, {_id: a7d3aaa8-9654-4535-b6c5-b147ff0d8eb3, _owner: 1d3480e5-0eda-47ef-8406-38d89bf15ded, _createdDate: 2022-05-08T22:35:38.398Z, discountedPrice: $81.59, _updatedDate: 2022-05-08T22:39:52.801Z, getDealLink: https://amzn.to/3ymXGLe, brands: [Amazon], originalPrice: $199.99, title: 2 Pack Stadium chairs for bleachers with back support, amazonlogo: wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346, link-items-all: /items/, link-items-title: /items/2-pack-stadium-chairs-for-bleachers-with-back-support})

How to retrive children from a single object intead of array in json-server?

I am using json-server for mock-backend to retrive children form a single object.
The parent table sentinel and the child table sensor
As you can see the sensors is an array and sentinel is an object.
I have used http://localhost:3000/sentinel?_embed=sensors but the response is not what i am expecting, because I want sensors: [{id: 1}, {id: 2}, ecc]
The official documentation shows that are two ways to retrive two tables:
_embed (include children) and _expand (include parent).
How could I achive this result?
Given that sentinel is a single object in your db.json and you can't have more than one sentinel it is not clear to me how your query is different from retrieving all sensors with sentinelId=10:
/sensors?sentinelId=10
In fact if you try this API:
/sentinel/10/sensors
it will work, because json-server rewrite the url exactly to the previous query.
If for some reason you don't want to use the sentinel id directly in the query, the other option is to use json-server as a module and define a custom route with the logic you need. Here's a basic example that exposes a /sentinel/sensors API and retrieve sentinel data along with the sensors whose sentinelId equals to the current sentinel id:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;
server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors', (req, res) => {
const sentinel = db.get('sentinel').value();
const sensors = db
.get('sensors')
.filter({ sentinelId: sentinel.id })
.value();
res.send({ ...sentinel, sensors: sensors });
});
server.use(router);
server.listen(3001, () => {
console.log('Mock server is running on port ' + 3001);
});
That would give you a response like this:
{
"id": 10,
"name": "Sentinel",
"sensors": [
{
"id": 1,
"sentinelId": 10
},
{
"id": 2,
"sentinelId": 10
}
]
}
Here's a stackblitz

JSON multiple alias names angular 8

I have below interface.
interface ProductJson {
id: number;
name: string;
price: number;
}
I want to have multiple alias names for price, like price and alias names: rate, etc. How can I read json data attribute 'rate' for 'price' and also read 'price' too.
You can use a custom serializer to create aliases between fields:
Example using #kaiu/serializer:
class ProductJson {
id: number;
name: string;
#FieldName('rate')
price: number;
}
Or you can also create a getter method and use the serializert to map your JSON to a class instance in order to use your method directly, see https://kaiu-lab.github.io/serializer/ for in-depth stuff.
One way is to maintain a group of attribute names that you want to alias.
And then add the interface property price to the json itself, if it contains the aliased properties like rate or amount.
Now you can simply access price from else where, which should give the same value
Ex:
var price_group = ['price', 'rate', 'amount'];
var some_other_group = []
var resp = {rate: 200, p: 12}
var resp2 = {price: 300, p: 12};
Object.keys(resp).forEach(key => {
if(price_group.indexOf(key) > -1){
resp.price = resp[key]
}
});
console.log(resp.price)
Object.keys(resp2).forEach(key => {
if(price_group.indexOf(key) > -1){
resp.price = resp[key]
}
});
console.log(resp2.price)
I'm not sure you can do that tbh.
You can easily do it by programming your stuff that reads/writes the json to accept stuff like rate, price, moolah and just write it as
{
price: number
}
edit: what i'm saying is you take the user input or any other input that specifies something like {moolah: 30} and you take that '30' and put it on {price: 30} in your json.

Remove duplicate object copies from array of objects

I have an array of objects that I get from an API. The property names are dynamic (meaning I don't have an extensive list of all of them). How can I get an array of all distinct objects? The contract specifies that if key is equal value is also equal. I tried to look around but I found nothing quite like this problem.
[ 20:31:28
{
'product-management': 'Product management'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
}
]
Spread the array into Object.assign() to merge all objects to a single one. Since all objects properties are unique, this will leave only one key (and value) from the duplicates. Then convert to [key, value] pairs with Object.entries(), and map back to individual objects:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([k, v]) => ({ [k]: v }))
console.log(result)
Going with #Bergi's suggestion, you can also convert this to a saner API while removing duplicates:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([key, value]) => ({ key, value }))
console.log(result)

How to group orders by different cities using Laravel, MySql, JSON

Trying to build a report result of orders related information of a laravel project. But struggling to find out a solution on a specific data structure.
My Request :
// Date Ranges
$fromDate = $this->request->fromDate;
$toDate = $this->request->toDate;
So the result should be within a date range.
My orders table :
order_id order_addresses grand_total
------------------------------------------
1 JSON DATA 3,000.00
2 JSON DATA 2,000.00
3 JSON DATA 1,500.00
So My JSON DATA looks like this :
{
"delivery_address":{
"House":"Offline House",
"Street":"Offline Road",
"Area":"Offline Area",
"PostCode":"1230",
"City":"City1",
"Country":"Country1",
"ContactPerson":"Offline User",
"ContactNumber":"01XXXXXXXX"
}
}
I just want the response as :
{
"orders": 3, // How many orders are there in that particular city
"totals": "5,500.00", // Total how much the cost of orders in that city
"groupby": "City1",
},
{
"orders": 5,
"totals": "7,500.00",
"groupby": "City2",
},
...,
...
I am seeking a solution using query builder in laravel with MySQL.
This is an existing project so I can't really change the structure how it was built. So, any suggestions on how I can extract the cities from JSON DATA having relation with the orders identity along with the totals and all.
I just need the order_ids I think city wise then I can structure my result anyway I like to achieve end result.
If anything confusion here, please let me know so that I can make it clear.
Thanks in Advance !
I would suggest grouping fetched data using Laravel Collection functions.
Order Model
class Order extends Model {
// This will cast data to native types.
// so order_address json string to array
protected $casts = [
'order_addresses' => 'array',
];
}
Controller function
// Fetch orders from the database as you usually do
// without considering about grouping.
// with your conditions.
// I will simply use all() for example.
$orders = Order::all();
// First group by city
// Then map to get the result you want.
$groupedOrders = $orders->groupBy(function($order) {
// since we added it to the casts array in the model
// laravel will automatically cast json string to an array.
// So now order_address is an array.
return $order->order_addresses['City'];
})
->map(function($groupedOrders, $groupName) {
return [
'orders' => $groupedOrders->count(),
'totals' => $groupedOrders->sum('grand_total'),
'groupby' => $groupName,
];
});