cognito user attributes to plain object - javascript

I'm trying to convert the Cognito user attributes I get from CognitoIdentityServiceProvider listUsersInGroup to plain object but I didn't found any library or AWS function that does it... then I tried to implement it by myself
That's what I came up with:
{
...user,
Attributes: user.Attributes.map((x) => ({ [x.Name]: x.Value })),
}
But that makes an array with objects and I'm trying to create an object with all the attributes...
[
{
"sub": "dasfdasfd-vcfdgfd",
},
{
"website": "aba",
},
{
"address": "new",
},
]
here is an example of the user's data (the attributes can be different from user to user):
user a:
[
{
"Name": "sub",
"Value": "dasfdasfd-vcfdgfd",
},
{
"Name": "website",
"Value": "aba",
},
{
"Name": "address",
"Value": "new",
},
{
"Name": "email_verified",
"Value": "false",
},
{
"Name": "phone_number_verified",
"Value": "false",
}
]
user b:
[
{
"Name": "custom:age",
"Value": "0",
},
{
"Name": "custom:height",
"Value": "0",
},
{
"Name": "email",
"Value": "dsafdsa#gmail.com",
}
]

You can use reduce
{
...user,
Attributes: user.Attributes.reduce((acc, { Name, Value }) => ({...acc, [Name]: Value }), {}),
}

Seems pretty simple just use loop. FYI : Array's map function always returns the array
function getAttributes(data){
let attributes = {};
for(let x of data){
attributes[x["name"]] = x["value"];
}
return attributes;
}
{
...user,
Attributes: getAttributes(user.Attributes)
}

Related

Filter an array using conditions stored in another array

I have this array of objects:
const parks = [
{
"properties": {
"name": "Park 1",
"parking": "",
"type": "park",
"picnic_area": 1
},
},
{
"properties": {
"name": "Park 2",
"parking": 1,
"type": "park",
"picnic_area": ""
},
}
];
The page have a list of checkboxes. When user check/uncheck one of then, a function generate an object with all the selected checkboxes:
{
"parking": true,
"picnic_area": true
}
My question is: how can I use this object to generate the conditions inside a filter() function? Something like:
const parksData = parks.filter(object => {
return object_condition_1 && object_condition_2;
});
For starters, you need to rename keys in the filters object so that they match properties' keys, that is, parking, not parkings. Then,
result = parks.filter(p =>
Object.keys(filters).every(key =>
Boolean(p.properties[key]) === Boolean(filters[key]))
)
This implements an AND condition, that is, only return objects that match all filters. If you need OR instead, replace every with some.
const parks = [
{
"properties": {
"name": "Park 1",
"parking": "",
"type": "park",
"picnic_area": 1
},
},
{
"properties": {
"name": "Park 2",
"parking": 1,
"type": "park",
"picnic_area": ""
},
}
];
const filter = {
"parkings": false,
"picnic_areas": true
};
console.log(parks.filter(park => (filter.parkings && !!park.properties.parking) || (filter.picnic_areas && !!park.properties.picnic_area)));

How to update deeply nested array of objects JavaScript

I have the following Array of object using this information I want to update array of object with value:a without mutating it directly (I am able to solve it using index but I don't want to update it using index) below is the code that I have tried so far
ccategory.map((item) =>
item.id === payload.id
? {
...item,
categoryItems: item.categoryItems.map(
(catItem) => catItem.categoryItemID === payload.categoryItemID
// stuck here how should I update categorySubItems?
),
}
: item
),
const payload={
"id": "4476c379-2c4f-4454-b59e-cae2f62fdfe2",
"categorySubItemsID": "c2cba4d6-5635-4b5c-acf3-b93b4d435aa9",
"categoryItemID": "fdb0e86b-a2d9-4029-8988-9f50121794d3",
"value": "a"
}
MyJSON looks like this
const category=[
{
"id": "4476c379-2c4f-4454-b59e-cae2f62fdfe2",
"categoryName": "Car",
"categoryFields": [
{
"name": "Car Name",
"type": "text",
"categoryID": "e9da78fb-d349-4b03-9b77-e3cc0dc57d25"
},
{
"name": "Price",
"type": "number",
"categoryID": "c9e147a6-b5d1-424b-99bf-a973ce189322"
}
],
"categoryItems": [
{
"categoryItemID": "fdb0e86b-a2d9-4029-8988-9f50121794d3",
"categorySubItems": [
{
"categorySubItemsID": "c2cba4d6-5635-4b5c-acf3-b93b4d435aa9",
"value": "",
"label": "Car Name",
"type": "text",
"categoryLinkID": "e9da78fb-d349-4b03-9b77-e3cc0dc57d25"
},
{
"categorySubItemsID": "01d5e1e7-3927-42a6-ad05-7399a5895096",
"value": "",
"label": "Price",
"type": "number",
"categoryLinkID": "c9e147a6-b5d1-424b-99bf-a973ce189322"
}
]
},
{
"categoryItemID": "f13237d7-abfd-40d3-ae35-0b59ddf5734e",
"categorySubItems": [
{
"categorySubItemsID": "2af389b9-03bc-41d3-86bb-8bf324ca3cb3",
"value": "",
"label": "Car Name",
"type": "text",
"categoryLinkID": "e9da78fb-d349-4b03-9b77-e3cc0dc57d25"
},
{
"categorySubItemsID": "934ef505-72bb-4d64-adf1-2aa5e928a539",
"value": "",
"label": "Price",
"type": "number",
"categoryLinkID": "c9e147a6-b5d1-424b-99bf-a973ce189322"
}
]
}
]
},
{
"id": "9882b210-2d99-43a3-8aea-9f7d7c88eeda",
"categoryName": "Bike",
"categoryFields": [
{
"name": "Bike Name",
"type": "text",
"categoryID": "73bee24c-ef64-4798-bc37-5fe90cbc8de7"
}
],
"categoryItems": []
}
]
In your inner .map(), if catItem.categoryItemID === payload.categoryItemID matches, you can return a new object that has an updated categorySubItems, which you can update by creating a new array by mapping catItem.categorySubItems. When mapping the sub category items, if your categorySubItemsID matches the one from the payload object, you can return a new updated object with a new value set to that of payload.value, otherwise, you can keep the original item, eg:
ccategory.map((item) =>
item.id === payload.id
? {
...item,
categoryItems: item.categoryItems.map((catItem) =>
catItem.categoryItemID === payload.categoryItemID
? {
...catItem,
categorySubItems: catItem.categorySubItems.map(subCatItem =>
subCatItem.categorySubItemsID === payload.categorySubItemsID
? {...subCatItem, value: payload.value}
: subCatItem
)
}
: catItem
),
}
: item
),
As you can see, this can get quite unwieldy. That's why it's often useful to use something like useImmer(), which allows you to directly modify a "draft" state value in an immutable way while keeping your state updates mutable.

How can i remove object from nested array?

I have this kind of json.
let arr1 = [
{
"packageReference": "1234",
"displayName": "Business",
"description": "Includes...",
"promotion": {
"packageReference": "1234",
"displayName": "$100 Standard",
"optionGroup": [
{
"displayName": "Access",
},
{
"displayName": "Contract"
},
{
"displayName": "Equipment"
},
{
"displayName": "Features"
},
{
"displayName": "Fees",
}
]
}
}
]
I need to remove only the object in the arr1[0].promotion.optionGroup where the displayName is 'Fees' and to return the new object without him.
You could do it by filtering the sub array like so:
let arr1 = [
{
"packageReference": "1234",
"displayName": "Business",
"description": "Includes...",
"promotion": {
"packageReference": "1234",
"displayName": "$100 Standard",
"optionGroup": [
{
"displayName": "Access",
},
{
"displayName": "Contract"
},
{
"displayName": "Equipment"
},
{
"displayName": "Features"
},
{
"displayName": "Fees",
}
]
}
}
];
arr1 = arr1.map(e => {
e['promotion']['optionGroup'] =
e['promotion']['optionGroup'].filter(s => s['displayName'] != 'Fees');
return e;
});
console.log(arr1);
// Get new array without the Fees one
const newGroup = arr1[0].promotion.optionGroup.filter(group => group.displayName !== 'Fees');
// Put new group into the object
arr1[0].promotion.optionGroup = newGroup;
Could also do it without creating a variable, but added it for cleanness.

Nested json object into single json objects with repeating parent details to construct html table

This is a nested json file and I am trying to arrange it in a readable format to display in a table
I tried to manually put all the keys and values with in a for loop but there should be an elegant way to achieve this and hence I am reaching SO.
The actual JSON is quite a nested one and needed time to execute data with 500k rows
The result should be enhanced JSON with parent values appearing for child values as well
var property = {
"data": [{
"ID": "123456",
"name": "Coleridge st",
"criteria": [
{
"type": "type1",
"name": "name1",
"value": "7",
"properties": []
},
{
"type": "type2",
"name": "name2",
"value": "6",
"properties": [
{
"type": "MAX",
"name": "one",
"value": "100"
}, {
"type": "MIN",
"name": "five",
"value": "5"
}
]
},
{
"type": "type3",
"name": "name3",
"value": "5",
"properties": [{
"type": "MAX1",
"name": "one6",
"value": "1006"
}, {
"type": "MIN2",
"name": "five6",
"value": "56"
}]
}
]
},
{
"ID": "456789",
"name": "New Jersy",
"criteria": [
{
"type": "type4",
"name": "name4",
"value": "6",
"properties": [{
"type": "MAX12",
"name": "one12",
"value": "10012"
}, {
"type": "MIN23",
"name": "five12",
"value": "532"
}]
}
]
}]
};
var output = [];
property.data.forEach(function (users) {
var multirows = {
id: users.ID,
name: users.name,
};
for (var i = 0; i < users.criteria.length; i++) {
var criterias = {
type: users.criteria[i].type,
name: users.criteria[i].name,
value: users.criteria[i].value,
}
var mat_contacts_rows;
if (!isEmpty(users.criteria[i].properties)) {
for (var j = 0; j < users.criteria[i].properties.length; j++) {
var property = {
type: users.criteria[i].properties[j].type,
name: users.criteria[i].properties[j].name,
value: users.criteria[i].properties[j].value
};
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
} else {
var property = [];
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
}
});
console.log(JSON.stringify(output, undefined, 2))
function isEmpty(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key))
return false;
}
return true;
}
I think this could be a great exercise to you to don't answer your question but to give you some tips. You should first look at : Lodash wish has a bunch of usefull method to help you doing what you'r trying to do.
In a second time you should avoir using .forEach or for loops and try using Array.prototype.map or Array.prototype.reduce

Re-arrage JSON values from existing values

The JSON provided is kind of unstructured and doesn't meet many of my
requirements. I have tried this many ways but does take a very long time
when I provide 100,000 records
Implemented Code
for (var f in stack.data) {
var field = new Object();
for (var o in stack.data[f]['field_values']) {
field[stack.data[f]['field_values'][o]['field_name']] = stack.data[f]['field_values'][o]['value'];
}
stack.data[f]['field_values'] = field;
}
console.log(JSON.stringify(stack, null, 2));
Input JSON:
var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}
Expected Output:
{
"data": [
{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": {
"Newsletter?": true,
"Parent": "Gigi Hallow",
"Birthday": "2018-04-29",
"Related": "2012-00121-Sass",
"Referral": "Don Ho",
"Spouse": "Wo Fat"
}
Sometimes "field_values can be empty. Need to check them as well
{
"id": 950821118875,
"name": "www.google.com",
"field_values": [],
}
This is mostly re-arranging the values. Here values becomes keys. There should actually be one liner to handle this, but i am run out of options.
Hope the question is clear
It would probably help to declare a variable to hold the array element, rather than doing 4 levels of indexing every time through the loop. You can also use destructuring to extract the properties of the object.
And use {} rather than new Object.
Even if this doesn't improve performance, it makes the code easier to read.
var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}
for (var f in stack.data) {
const field = {};
const fobj = stack.data[f];
for (var o in fobj.field_values) {
const {field_name, value} = fobj.field_values[o];
field[field_name] = value;
}
fobj.field_values = field;
}
console.log(JSON.stringify(stack, null, 2));

Categories

Resources