I would like to normalise a nested JSON data response which I get from the API. The data response contains agents who belong to multiple shifts. The relation between the entities are many-to-many association since, A shift can many agents and an agent can belong to many shifts. So I came across this normalizr utility where I tried to normalize the date to this form so I would be able parse this easier.
I tried to normalize to this form
{
entities : {
shifts:[{...}],
agents:[{...}]
}
}
import { normalize, schema } from 'normalizr';
import stubData from './stubData';
const agent = new schema.Entity('agents', {});
const day_agents = new schema.Entity('day_agents', {
agents: [agent]
});
const shift = new schema.Entity('shifts', {
day_agents
});
const normalizedData = normalize(stubData, shift);
stubData:
"shifts": [{
"id": 1,
"name": "Shift 1",
"start_time": "9:00",
"end_time": "5:00",
"day_agents": {
"10/4/2019": {
"leaves": 1,
"agents": [
{
"id": 1,
"name": "a",
"email": "a#b.co",
"group_id": 1,
"Leave": false
},
{
"id": 2,
"name": "b",
"email": "b#b.co",
"group_id": 1,
"Leave": false
}
]
},
"11/4/2019": {
"leaves": 1,
"agents": [{
"id": 4,
"name": "c",
"email": "c#c.co",
"group_id": 2,
"Leave": true
},
{
"id": 5,
"name": "d",
"email": "d#d.co",
"group_id": 2,
"Leave": false
}
]
}
}
}]
Related
I have an Object which is having some properties like this:
obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
I want covert the array of objects (operationIds and ratingIds) inside the object to array of properties, I'm receiving this object and I want to apply the change on it and supply another method so it should look like this:
obj1={
"id": 2,
"description": "",
"operationIds": [
1
],
"ratingIds": [
1,
4,
8
],
"timestamp": "AAAAAAAGJ6c=",
"estimatedUtilReconciliationApplies": true
}
I was able to do it but in a verry ugly way, is there a more simple and clear way to accomplish this ?
let x = {...obj} as any;
let ar1 = x.operationIds;
const arr1= ar1.map(function (obj) {
return obj.id;
});
let ar2 = x.ratingIds;
const arr2= ar2.map(function (obj) {
return obj.id;
});
x.operatingEnvironmentIds = arr1;
x.thrustRatingIds = arr2;
You can use spread operator and map
let obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
console.log({
...obj1,
operationIds:obj1.operationIds.map(elem => elem.id),
ratingIds:obj1.ratingIds.map(elem => elem.id),
})
And as a function
let obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
let transform = (obj) => {
return({
...obj,
operationIds:obj.operationIds.map(elem => elem.id),
ratingIds:obj.ratingIds.map(elem => elem.id),
})
}
let transformed = transform(obj1)
console.log(transformed)
We loop the array and use the Object.assign() method to convert an array of objects to a single object. This merges each object into a single resultant object.
The Object.assign() method also merges the properties of one or more objects into a single object.
the reason I need the code to work in core javascript is the tool we use, it uses Rhino from mozilla, so it cannot contain objects or methods related to manipulation of web pages.
I am trying to compare data from two json files using core javascript, When the order_number and extid is same we compare the count(fullfilments.line_items) and quantity(which is the sum of all the quantities of all line items under that fulfillment, fullfilments.line_items.quantity) . If the order_number and ext_id combination match along with count and sum above, do nothing. If no match, we remove the refund. the code works fine in Visual Studio. I am new to pentaho and I think the code needs to be changed as only core js works with this tool.
In the Orders file are sample json structure, for example Order_number (66 in this case) need to calculate and compare the count of line items(6 in this case) along with the Quantity of items(7 in this case), if it doesn't match need to remove Object Refund along with its elements, else No Changes.
``````Sample File````````
[
{
"app_id": 111,
"fulfillments":
[
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 66,
"ext_id": 110,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 398000,
"order_id": 450005,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 67,
"ext_id": 114,
"refunds": [
{
"id": 81,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 2
},
{
"id": 768,
"quantity": 2
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 68,
"ext_id": 113,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
}
]
```````````````````````````````json`````````````
//resultset file content
[
{
"order_number": 66,
"extid":110,
"line_items_count": 6,
"quantity": 7
},
{
"order_number": 67,
"extid":114,
"line_items_count": 4,
"quantity": 7
},
{
"order_number": 68,
"extid":113,
"line_items_count": 4,
"quantity": 6
}
]
`````````````````````````````````````````````````Code`````````````````
/**
* orders.json file has some sample orders
* resultset.json file has results from sql Lookup to the orders.
*
*/
const orders = require('./orders.json');
function compare(order) {
let isMatched = false;
let resultSet = require('./resultset.json');
let result = resultSet.find(function (item) {
return item.order_number === order.order_number;
});
if (
result &&
result.line_items_count === order.items &&
result.quantity === order.quantity
) {
isMatched = true;
}
return isMatched;
}
function fixOrders(orders) {
orders.map(function (order) {
let { order_number, line_items } = order;
let quantity = line_items.reduce(function (quantity, line_item) {
return (quantity += line_item.quantity);
}, 0);
if (!compare({ order_number, items: line_items.length, quantity })) {
delete order.refunds;
}
});
return orders;
}
let fixedOrders = fixOrders(orders);
console.log(fixedOrders);
// store in output.js
//========================================
// var fs = require('fs');
// fs.writeFile('outputFile.json', JSON.stringify(fixedOrders), (err) => {
// if (err) console.log(err);
// else {
// console.log('File written successfully\n');
// // console.log('The written has the following contents:');
// // console.log(fs.readFileSync('outputFile.json', 'utf8'));
// }
// });
[PDI Flow][1]
[1]: https://i.stack.imgur.com/3OzQE.png
I'm trying to filter some objects based on another array of objects. So I'm getting data from an API. These are for example receipts:
[
{
"id": 1,
"name": "test",
"category": {
"id": 1,
"name": "Cookies",
},
},
{
"id": 2,
"name": "test2",
"category": {
"id": 2,
"name": "Candy",
},
}
]
Then I'm trying to filter the objects on the category name based on another array of categories.
I've created a function for this:
function onSelectCategory(category) {
let receiptsList = receipts.filter((a) =>
a.category.includes(category.name)
);
setReceiptsView(receiptsList);
setSelectedCategory(category);
}
const category = [ { "id": 2, "name": "Candy" } ];
onSelectCategory(category);
When I run this function, I get an empty Array []. I can't really figure out what I'm doing wrong.
Since the param seems to be an array of objects, you need to use Array#some for comparison instead:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const receiptsList = receipts.filter(({ category }) =>
categories.some(({ name }) => name === category.name)
);
console.log(receiptsList);
Another solution using Set:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const categorySet = new Set(categories.map(({ name }) => name));
const receiptsList = receipts.filter(({ category }) =>
categorySet.has(category.name)
);
console.log(receiptsList);
Assuming that category (the parameter) is a string, the issue is that you are attempting to get the attribute name from the string, when you should be comparing the string to the object.
Try this:
a.category.name == category;
instead of
a.category.includes(category.name)
I may be wrong aboout assuming that category is a string, please clarify by telling us what the parameter category is equal to.
I have an object that has a whole host of arrays and properties. There is a property called targetProperty which appears in various places of the object.
I have a function where if the user clicks yes, every instance of that property needs to be reassigned to a new value.
The problem is the function that I used for assigning a new value doesn't work in this senario:
reassingPropertyInObj(obj, status) {
if (typeof obj === 'object' && obj !== null) {
obj.targetProperty = status;
for (const key in obj) {
this.handleExpandCollapseClick(obj[key], status);
}
}
},
Does anyone have a solution for this? Also can't use JSON.parse() or anything like that because the properties need to stay reactive for later reassignment if needed by the user.
Below is an example of one object:
{
"id": 16,
"ref_study_id": "3412333",
"title": "SomePersonNameOne",
"capabilities_available": [
{
"id": 75,
"name": "Clinical Data",
},
{
"id": 538,
"name": "RK's Capability",
}
],
"capabilities_impacted": [],
"businessImpact": {
"id": 2,
"name": "Medium"
},
"sites_impacted": [],
"sites_available": []
},
{
"id": 6,
"ref_study_id": "123124",
"title": null,
"capabilities_available": [
{
"id": 37,
"name": "Clinical Site Experience,
},
{
"id": 41,
"name": "Experience",
}
],
"capabilities_impacted": [
{
"id": 37,
"name": "Information Exchange",
"is_study_level": false,
"businessImpact": {
"id": 2,
"name": "Medium"
}
},
{
"id": 39,
"name": "IT/Data Experience",
"is_study_level": false,
"businessImpact": {
"id": 2,
"name": "Medium"
}
},
{
"id": 34,
"name": "Mgmt & Storage",
"is_study_level": false,
"businessImpact": {
"id": 3,
"name": "Minor"
}
}
],
"businessImpact": {
"id": 2,
"name": "Medium"
},
"sites_impacted": [],
"sites_available": []
},
And the property in question is businessImpact. As you can see it appears by itself as a property and inside array (and sometimes those arrays of arrays of their own).
I setup a function like:
arrayOfProperties.forEach((property) => {
obj[property].forEach((o) => {
o.businessImpact = newVal;
});
});
But of course it doesn't go deep enough.
I have a list object returned from server,
example:
{
"items": [
{
"id": 1,
"role": "SYSTEM_ADMIN"
},
{
"id": 2,
"role": "SYSTEM"
},
{
"id": 3,
"role": "USER"
}
]
}
The problem here is that I want to set the rank value of each object in the above json follow the condition:
SYSTEM_ADMIN => rank: 3
SYSTEM => rank: 2
USER => rank 1
example:
{
"items": [
{
"id": 1,
"role": "SYSTEM_ADMIN",
"rank": 3
},
{
"id": 2,
"role": "SYSTEM",
"rank": 2
},
{
"id": 3,
"role": "USER",
"rank": 1
},
{
"id": 4,
"role": "SYSTEM",
"rank": 2
}
]
}
How do I use javascript quickly set rank values for the object without if else too much? thanks everyone
As some people suggested, it's best to do it on the server when you create the response.
If you still need to do it on the frontend for some reason, you can create a constant map that stores each role value's rank in an object map:
const rankMap = {
SYSTEM_ADMIN: 3,
SYSTEM: 2,
USER: 1
};
const data = {
"items": [{
"id": 1,
"role": "SYSTEM_ADMIN"
},
{
"id": 2,
"role": "SYSTEM"
},
{
"id": 3,
"role": "USER"
}
]
}
data.items = data.items.map(item => ({
...item,
rank: rankMap[item.role],
}));
console.log(data);
You can create an object which contains rank and then just use map:
let ranks = {SYSTEM_ADMIN: 3, SYSTEM: 2, USER: 1};
let result = items.map(({id, role})=> ({id, role, rank: ranks[role]}));
An example:
let items = [
{
"id": 1,
"role": "SYSTEM_ADMIN"
},
{
"id": 2,
"role": "SYSTEM"
},
{
"id": 3,
"role": "USER"
}
];
let ranks = {SYSTEM_ADMIN: 3, SYSTEM: 2, USER: 1};
let result = items.map(({id, role})=> ({id, role, rank: ranks[role]}));
console.log(result)
I would keep a list of the roles and their respective ranks in a dictionary. The response can then very simply be mapped
let response = {
items: [
{
"id": 1,
"role": "SYSTEM_ADMIN",
},
{
"id": 2,
"role": "SYSTEM",
},
{
"id": 3,
"role": "USER",
},
{
"id": 4,
"role": "SYSTEM",
}
]
}
let rankMap = {
"SYSTEM_ADMIN": 3,
"SYSTEM": 2,
"USER": 1
}
response.items.forEach(i => i['rank'] = rankMap[i.role]);
console.log(response);