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);
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.
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 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
}
]
}
}
}]
I'm working on django rest and angular. This json array is coming from server and contains category and subcategory values.
my code will create category and related subcategory in separate keys of array. But i want keep subcategory as a array in object in same object.
Result should be like this:
[{"title":"title of category","sub":[array of related sub]} , ...]
mycode:
public data = SERVERRESPONE;
public categories = [];
this.data.filter(c => c.parent_id === null).map(c => <{ title: {}; subcategories: {} }>{
title: {"title":c.title},
subcategories: this.data.filter(sc => sc.parent_id === c.cat_id).map(sc => sc.title)
}).forEach(c => {
this.categories.push([c.title, [c.subcategories]]);
});
server response :
[
{
"id": 5,
"cat_id": 0,
"parent_id": null,
"title": "web development"
},
{
"id": 6,
"cat_id": 1,
"parent_id": null,
"title": "android development"
},
{
"id": 7,
"cat_id": null,
"parent_id": 0,
"title": "php"
},
{
"id": 8,
"cat_id": null,
"parent_id": 1,
"title": "java"
}
]
it is nice question but it has very easy solution!
const array = [
{
"id": 5,
"cat_id": 0,
"parent_id": null,
"title": "web development"
},
{
"id": 6,
"cat_id": 1,
"parent_id": null,
"title": "android development"
},
{
"id": 7,
"cat_id": null,
"parent_id": 0,
"title": "php"
},
{
"id": 8,
"cat_id": null,
"parent_id": 1,
"title": "java"
}
]
let result = []
for (let key of array) {
if (key.parent_id === null) {
let new_key = key,
sub = []
for (let iterator of array)
if (iterator.parent_id === key.cat_id)
sub.push(iterator)
new_key.sub = sub
result.push(new_key)
}
}
console.log(result)
I want a method that goes through a posts array, and returns a new array with only the elements that match a certain value of the userId property.
For example:
let postsArr = [
{
"userId": 1,
"id": 1
},
{
"userId": 1,
"id": 2
},
{
"userId": 2,
"id": 3
},
{
"userId": 2,
"id": 4
},
{
"userId": 3,
"id": 5
}
]
Say I want to return only the items with userId: 2.
(Something like...)
let filteredArr = postsArr.method( post => post.userId === 2)
Which would (ideally) return:
[
{
"userId": 2,
"id": 3
},
{
"userId": 2,
"id": 4
}
]
I'm sure it would be something like .map() or .filter(), but I can quite get my head round how to do it, or what the best method is in this case.
Any help appreciated.
Your pretty much there to be honest..
let postsArr = [
{
"userId": 1,
"id": 1
},
{
"userId": 1,
"id": 2
},
{
"userId": 2,
"id": 3
},
{
"userId": 2,
"id": 4
},
{
"userId": 3,
"id": 5
}
];
var farray = postsArr.filter((a) => a.userId === 2);
console.log(farray);
In ES5. We used to do this.
var newarray = postsArr.filter(function(obj){
return obj.userId === 2
})