Convert Dynamic List into JSON object - javascript

I am allowing my users to create different roles for themselves within my svelteKit application.
I have a text input with a button that adds that value to an array and shows in the div below.
I need to convert the array into a tiered JSON object so I can add it to my Postgres database role_permissions column as JSONB. I have tried JSON.stringify() and JSON.parse() but I cannot get it to work.
Ideally formatted like this:
{
"role_name"{
"permission": true,
"permission": true,
...
}
"role_name_2"{
"permission": true,
"permission": false,
...
}
}
While my users can create roles with custom names the permissions available are all the same e.g.:
can_add_members: false,
can_delete_members: false,
can_edit_members: false,
can_create_roles: false,
can_delete_roles: false,
can_edit_roles: false,
can_assign_roles: false,
can_create_projects: false,
can_delete_projects: false,
can_edit_projects: false,
can_publish_projects: false,
can_view_projects: false,
can_assign_members_to_projects: false,
I can't figure out how to convert the object into a tiered JSON format. I know I need some sort of key outside of each object but I do not know how to do that.
This is how they appear in console.log()
{name: "Partner", can_add_members: false, can_delete_members: false, can_edit_members: false, can_create_roles: false, …}
{name: "Associate Partner", can_add_members: false, can_delete_members: false, can_edit_members: false, can_create_roles: false, …}
The actual code:
let newItem = '';
// An array of the roles names that will also be saved to the database as is.
let roleList = [];
// The array that needs to be converted to JSON
let roleListWithPermissions = [],
function addToList() {
roleList = [...roleList, {text: newItem,}];
roleListWithPermissions = [...roleListWithPermissions, {
"name": newItem,
"can_add_members": false,
"can_delete_members": false,
"can_edit_members": false,
"can_create_roles": false,
"can_delete_roles": false,
"can_edit_roles": false,
"can_assign_roles": false,
"can_create_projects": false,
"can_delete_projects": false,
"can_edit_projects": false,
"can_publish_projects": false,
"can_view_projects": false,
"can_assign_members_to_projects": false
}];
newItem = '';
console.log("ROLE LIST",roleList)
console.log("PERMISSIONS LIST",roleListWithPermissions)
}

One approach is below, with explanatory comments in the code:
// the original Object as described/shown in the question:
let source = [{
name: "Partner",
can_add_members: false,
can_delete_members: false,
can_edit_members: false,
can_create_roles: false,
},
{
name: "Associate Partner",
can_add_members: false,
can_delete_members: false,
can_edit_members: false,
can_create_roles: false,
}
],
// here we use Array.prototype.map() to iterate over the Array of Objects:
rolePermissions = source.map(
// using destructuring assignment to retrieve the 'name'
// property from the Array-element (the Object),
// and assigning all remaining property-value pairs
// to the 'rest' variable:
({
name,
...rest
}) => {
// here we return a new Object, with the computed value of the
// 'name' variable to set the property equal to the value of the
// variable rather than the String of 'name':
return {
// and the property-value equal to the Object containing the
// rest of the key-value pairs:
[name]: rest
};
}),
// converting the Array of Objects into a JSON string:
jsonRolePermissions = JSON.stringify(rolePermissions);
// logging that JSON string to the console:
console.log(jsonRolePermissions);
Reference:
Array.prototype.map().
Destructuring assignment.
JSON.stringify().
Object initializer.

you can transform roleListWithPermissions array to an object.
const finalResult =
roleListWithPermissions.reduce((result, current) => {
result[current.name]= {...current};
delete result[current.name].name;
return result;
}, {})

Related

Filtering array with Boolean giving unexpected results

I can't understand why the output is 17 its only returning the true values not the false values either that the false value are boolean also
function countSheeps() {
const array1 = [true, true, true, false,
true, true, true, true,
true, false, true, false,
true, false, false, true,
true, true, true, true,
false, false, true, true]
return array1.filter(Boolean).length;
}
the output is 17.
Boolean returns true if its argument is truthy and false otherwise. Array#filter only keeps the values for which the callback returns true (or a truthy value). Here, Boolean is the callback and since all the values in the array are already booleans, only the true values are retained. If you want to keep all values that are primitive booleans, you can use typeof in a custom callback function.
const array1 = [true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, true ,
true, true, true, true ,
false, false, true, true]
console.log(JSON.stringify(array1.filter(Boolean)));
console.log([true, true, false, true, false, 1, "test"]
.filter(x => typeof x === 'boolean'));
Array.prototype.filter() works by evaluating the return value given to it each iteration. A new array will be returned, but only values/iterations where a truthy value was returned in the block. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Now take a look at what that function Boolean does: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean
Essentially, you're passing every value from array1 to filter, and for each of those iterations you're returning the return value from calling that Boolean function with the element in question. When you pass true to that function, it returns true, so that value will end up in the array returned by the filter method. When you pass false, the Boolean function returns false in the block to filter, which means the filter method will NOT include that value in its return value.
console.log(Boolean(true)); // This returns true, so all these values from array1 end up in the final array that filter returns.
console.log(Boolean(false)); // This returns false, which means for that iteration you're returning a falsey value to the filter method, therefore filter will not keep select/keep the element in question.
filter array method : Filters array on the basis of condition provided inside.
arr = [1,2,3,4,5,6];
arr.filter(ele => ele>3)
output: Array(3) [ 4, 5, 6 ]
Boolean : Boolean returns true if value is true
Boolean(true)
output: true
And vice versa
Boolean(false)
output: false
Here your checking Boolean(true), in case of true value it is counting but in case of false it is filtering out.
To correct this scenario, Use type checking inside filter function.
function countSheeps() {
const array1 = [true, true, true, false,
true, true, true, true,
true, false, true, false,
true, false, false, true,
true, true, true, true,
false, false, true, true]
return array1.filter(item => typeof(item)==='boolean').length;
}

How do I filter an array when the value is true and display only the key?

This is my array:
array: [{
_id: 5f62b2bc84a1ef1c5c48d1af,
eeid: '300094E6E2',
adminOrganization: true,
adminEmployees: false,
adminAssets: true,
adminConsumables: true,
adminWarehousing: false,
grantBy: '300094E6E2',
grantDate: 2020-10-04T11:46:28.548Z,
__v: 0
}]
I want to filter only true values and display only the key: Below is my desired result:
resultingArray = ['adminOrganization', 'adminAssets', 'adminConsumables']
You can use Object.key to get all keys in object and filter field value is true as
var filtered = Object.keys(obj[0]).filter(function(key) {
return obj[0][key] == true;
});
obj = [{
_id: '5f62b2bc84a1ef1c5c48d1af',
eeid: '300094E6E2',
adminOrganization: true,
adminEmployees: false,
adminAssets: true,
adminConsumables: true,
adminWarehousing: false,
grantBy: '300094E6E2',
grantDate: '2020-10-04T11:46:28.548Z',
__v: 0
}]
;
var filtered = Object.keys(obj[0]).filter(function(key) {
return obj[0][key] == true;
});
console.log(filtered)

Object Keys Filtering

How can I pass object keys into an array that are true. So that I can use this array for filtering?
Example Object:
let results = [
{name: marc, isAlumnus: true, isScholar: true, isTrustee: false},
{name: franz, isAlumnus: false, isScholar: true, isTrustee: false},
{name: Hugo, isAlumnus: true, isScholar: true, isTrustee: false},
]
And the attempt of a function!
getActiveStatusGroups (results) {
let res = [];
res = results.map((item) => {
if (item) {
res.push('isScholar');
}
});
return res;
},
let statusArray = getActiveStatusGroup(this.results)
You can get an array of the property names from Object.keys, or an array of [name, value] arrays from Object.entries, depending on what you want to do.
It's kind of hard to tell what output you want as a result, but for instance, this returns an array of arrays, where the inner arrays are the names of the properties for which the value was truthy:
getActiveStatusGroups(results) {
return results.map(entry =>
Object.keys(entry).filter(key => entry[key])
);
}
Live Example:
let results = [
{isAlumnus: true, isScholar: true, isTrustee: false},
{isAlumnus: false, isScholar: true, isTrustee: false},
{isAlumnus: true, isScholar: true, isTrustee: false},
];
function getActiveStatusGroups(results) {
return results.map(entry =>
Object.keys(entry).filter(key => entry[key])
);
}
console.log(getActiveStatusGroups(results));
Filtering is pretty simple in JavaScript
The methods name is right there in your title, yet you failed to recognize it. Use filter instead of map. The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Here's your code
let results = [
{name: marc, isAlumnus: true, isScholar: true, isTrustee: false},
{name: franz, isAlumnus: false, isScholar: true, isTrustee: false},
{name: Hugo, isAlumnus: true, isScholar: true, isTrustee: false},
]
getActiveStatusGroups(group) {
// returns the element if the condition is true
return results.filter(result => result[group])
}
That's it
console.log(getActiveStatusGroups('isAlumnus'))
console.log(getActiveStatusGroups('isScholar'))
console.log(getActiveStatusGroups('isTrustee'))

Display the JSON information into a drop down.Angularjs

This is my JSON data:
{
result: 1,
vote_time_slots: {
2016-08-07: {
diff: 1080,
slots: {
08:42: false, 09:36: false, 06:54: false, 04:30: false,
09:18: false, 09:00: false, 08:24: false, 05:42: false,
06:00: false, 10:12: false, 08:06: false, 06:36: false,
07:12: false, 07:48: false, 05:24: false, 06:18: false,
09:54: false, 07:30: false, 10:30: false, 05:06: false,
04:48: false
}
},
2016-07-25: {
diff: 1080,
slots: {
08:42: false,
09:36: false,
06:54: false,
}
},
I want the time slots like 08:42, 09:36 and so on to be getting into a drop down.
please tell me how to navigate to slots field and get only slot values Filtered on false (which is value)
<li ng-repeat="c in eventTimings | filter: ????:false"><a>{{(c)}}
how to show based on filter also?
If i have true value the respective time slot should not show in drop down.
Try like this:
slots = {
"08:42": false, "09:36": false, "06:54": false, "04:30": false,
"09:18": false, "09:00": false, "08:24": false, "05:42": false,
"06:00": false, "10:12": false, "08:06": false, "06:36": false,
"07:12": false, "07:48": false, "05:24": false, "06:18": false,
"09:54": false, "07:30": false, "10:30": false, "05:06": false,
"04:48": false
};
var arr = [];
for(var prop in slots) { arr.push(prop); }
console.log(arr);
From here on you repeat on the arr
ng-repeat="opt in arr" ...
You will have to iterate over the properties of slots (since it is in object format). Please do search in stackoverflow before asking a question.
See if the answer in following link helps and write a custom filter using the logic:
Iterate through object properties
You can try this simple solution:
<li ng-repeat="(key, value) in data.slots" ng-if='!value'>{{key}}</li>
Another approach - to create custom filter:
HTML:
<li ng-repeat="(key, value) in data.slots | custom : false">{{key}}</li>
Javascript:
.filter('custom', function() {
return function(input, search) {
var result = {};
angular.forEach(input, function(value, key) {
if (value == search) {
result[key] = value;
}
});
return result;
}});

Why is the Argument taken as an Object and not as an Array?

Why is the Argument taken as an Object and not as an Array??
Question Description:
Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
For example,
[true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, true ,
true, true, true, true ,
false, false, true, true]
The correct answer would be 17.
My Solution:
function countSheeps(arrayOfSheeps)
{
var num=0;
for(var i=0; i<arrayOfSheeps.lenght(); i++)
{
if(arrayOfSheeps[i]==true){ num=num+1; }
}
return num;
}
Test Cases:
var array1 = [true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, true ,
true, true, true, true ,
false, false, true, true ];
Test.expect(countSheeps(array1) == 17, "There are 17 sheeps in total")
Output:
TypeError: Object true,true,true,false,true,true,true,true,true,false,true,false,true,false,false,true,true,true,true,true,false,false,true,true has no method 'lenght'
at countSheeps
0 Passed
0 Failed
1 Errors
Process took 110ms to complete
P.S. I am a newbie to JS.
Based on the comments you should correct lenght() to length
function countSheeps(arrayOfSheeps)
{
var num=0;
for(var i=0; i<arrayOfSheeps.length; i++)
{
if(arrayOfSheeps[i]==true){ num++; }
}
return num;
}
Why is the Argument taken as an Object and not as an Array??
Because all arrays are objects in javascript. That error message basically contains the type of the reference base (which is an object, as opposed to a primitive type such as string/number/boolean) and the .toString() representation of that object (which in the case of your array of booleans just is the same as arrayOfSheeps.join(',')).
It does not say that arrayOfSheeps wasn't an array. It just says that the array object is an object.
public int countSheeps(Boolean[] arrayOfSheeps) {
var num=0;
for(var i=0; i<arrayOfSheeps.length; i++)
{
if(arrayOfSheeps[i]!=null && arrayOfSheeps[i]==true){ num=num+1; }
}
return num;
}

Categories