How to hide object property to display using angular ng-model? - javascript

I want to hide _id to display on UI using ng-model , I see alot of examples of filtering data using ng-repeat but i did not find angular solution to achieve this task using ng-model.How can hide _id property to display ?
main.html
<div ng-jsoneditor="onLoad" ng-model="obj.data" options="obj.options" ></div>
Ctrl.js
$scope.obj.data = {
"_id": "58a3322bac70c63254ba2a9c",
"name": "MailClass",
"id": "MailTask_1",
"createdBy": "tyuru",
"__v": 0,
"properties": [{
"label": "Java Package Name",
"type": "String",
"editable": true,
"binding": {
"type": "property",
"name": "camunda:class"
},
"$$hashKey": "object:29"
}],
"appliesTo": [
"bpmn:ServiceTask"
]
}
var json = {};
function loadCurrentUserAndTemplate() {
AuthService.getCurrentUser()
.then(function(resp) {
$scope.currentUser = resp.data.id;
// console.log($scope.currentUser);
userTemplate($scope.currentUser);
});
}
loadCurrentUserAndTemplate();
$scope.obj = {
data: json,
options: {
mode: 'tree'
}
};
var privateFields = removePrivateFields($scope.obj.data, ['_id', '__v']);
// add private fields back to $scope.obj.data before POST
var modifiedData = Object.assign({}, $scope.obj.data, privateFields);
function removePrivateFields(obj, props) {
var output = {};
props.forEach(function(prop) {
if (obj.hasOwnProperty(prop)) {
output[prop] = obj[prop];
delete obj[prop];
}
});
return output;
}
function userTemplate(user) {
// console.log('inside template',$scope.currentUser);
templateService.getUserTemplates(user)
.then(function(response) {
// console.log('userTemplate',response.data);
// console.log(response.data.length);
$scope.displayedTemplates = response.data;
if (response.data.length !== 0 && response.data !== null) {
$scope.obj.data = response.data[0];
}
}

you can create a function like removePrivateFields to strip the private fields from original object and attach them back to the modified object before submitting to server
// for testing
var $scope = { obj: {} };
var jsonData = {
"_id": "58a3322bac70c63254ba2a9c",
"name": "MailClass",
"id": "MailTask_1",
"createdBy": "tyuru",
"__v": 0,
"properties": [{
"label": "Java Package Name",
"type": "String",
"editable": true,
"binding": {
"type": "property",
"name": "camunda:class"
},
"$$hashKey": "object:29"
}],
"appliesTo": [
"bpmn:ServiceTask"
]
};
var privateFields = removePrivateFields(jsonData, ['_id', '__v']);
// private fields got removed form actual jsonData
$scope.obj.data = jsonData;
console.log($scope.obj.data);
// once edit
// add private fields back to $scope.obj.data before POST
var modifiedData = Object.assign({}, $scope.obj.data, privateFields);
console.log(modifiedData);
function removePrivateFields(obj, props) {
var output = {};
props.forEach(function(prop) {
if (obj.hasOwnProperty(prop)) {
output[prop] = obj[prop];
delete obj[prop];
}
});
return output;
}

It would be both more performant and along Angular best practices to instead delegate this functionality into your controller or the service fetching the object.
Ideally, you want to perform any object manipulation or formatting within an Angular service, but you could also do it within your controller (probably fine if you're just instantiating your JSON editor with mock data).

Related

How to create a json object from another json object using JavaScript?

I am really junior with JavaScript and json, so I have this JSON input, and I need to get all that information in the "properties" object to create a new JSON object with just that information.
I'm using a base code like this one, but this is just returning {}.
exports.step = function(input, fileInput) {
var alert = {
'Properties': input.alert.properties
}
return JSON.stringify(alert, undefined, 1);
};
Original JSON:
"value": {
"id": "12345",
"entity": {
"_integrationDefinitionId": "7a6764",
"_integrationName": "Apple Main",
"_beginOn": "2021-09-01T02:20:06.189Z",
"displayName": "apple-onev",
"_accountIdPartitioned": "12345|12",
"_class": [
"Deployment",
"Group"
],
"_version": 3,
"_integrationClass": [
"CiSSP",
"Infrastructure"
],
"_accountId": "123456",
"_id": "1e234567",
"_key": "arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456",
"_type": [
"aws_autoscaling_group"
],
"_deleted": false,
"_rawDataHashes": "1233456==",
"_integrationInstanceId": "54321",
"_integrationType": "aws",
"_source": "integration",
"_createdOn": "2021-07-19T23:19:19.758Z"
},
"properties": {
"webLink": "https://google.com",
"arn": "name",
"region": "us-west-2",
"name": "JonnyAndTheVibes",
"launchConfigurationName": "OtherName",
"minSize": 1,
"maxSize": 4,
"desiredCapacity": 1,
"defaultCooldown": 360,
"availabilityZones": "us-west-2a",
"LoadBalancerNames": "MoreInfo",
"healthCheckType": "EC2",
"healthCheckGracePeriod": 0,
"instanceIds": "InstanceName",
"subnetIds": "subnet",
"terminationPolicies": "Default",
"newInstancesProtectedFromScaleIn": false,
"serviceLinkedRoleARN": "aMoreInfo",
"tag.Name": "atag",
"tag.application": "othertag",
"tag.aws:cloudformation:logical-id": "moretagsp",
"tag.aws:cloudformation:stack-id": "taggigante",
"tag.aws:cloudformation:stack-name": "ydaleconlostags",
"tag.elasticbeanstalk:environment-id": "seguimosmetiendoletags",
"tag.elasticbeanstalk:environment-name": "tag",
"tag.env": "tag",
"tag.team": "tag",
"accountId": "tag",
"tag.AccountName": "tag",
"tag.Production": true,
"#tag.Production": "​"
}
}
I'm sure that it will be a simple solution.
You appear to be trying to grab properties from the wrong object. It should be value not alert.
const json = '{"value":{"id":"12345","entity":{"_integrationDefinitionId":"7a6764","_integrationName":"Apple Main","_beginOn":"2021-09-01T02:20:06.189Z","displayName":"apple-onev","_accountIdPartitioned":"12345|12","_class":["Deployment","Group"],"_version":3,"_integrationClass":["CiSSP","Infrastructure"],"_accountId":"123456","_id":"1e234567","_key":"arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456","_type":["aws_autoscaling_group"],"_deleted":false,"_rawDataHashes":"1233456==","_integrationInstanceId":"54321","_integrationType":"aws","_source":"integration","_createdOn":"2021-07-19T23:19:19.758Z"},"properties":{"webLink":"https://google.com","arn":"name","region":"us-west-2","name":"JonnyAndTheVibes","launchConfigurationName":"OtherName","minSize":1,"maxSize":4,"desiredCapacity":1,"defaultCooldown":360,"availabilityZones":"us-west-2a","LoadBalancerNames":"MoreInfo","healthCheckType":"EC2","healthCheckGracePeriod":0,"instanceIds":"InstanceName","subnetIds":"subnet","terminationPolicies":"Default","newInstancesProtectedFromScaleIn":false,"serviceLinkedRoleARN":"aMoreInfo","tag.Name":"atag","tag.application":"othertag","tag.aws:cloudformation:logical-id":"moretagsp","tag.aws:cloudformation:stack-id":"taggigante","tag.aws:cloudformation:stack-name":"ydaleconlostags","tag.elasticbeanstalk:environment-id":"seguimosmetiendoletags","tag.elasticbeanstalk:environment-name":"tag","tag.env":"tag","tag.team":"tag","accountId":"tag","tag.AccountName":"tag","tag.Production":true,"#tag.Production":"​"}}}';
function getAlert(dsta) {
// Destructure the properties object from the
// data's value property
const { properties } = data.value;
// Create a new object with it
const alert = { properties };
// Return the string
return JSON.stringify(alert, null, 2);
};
// Parse the JSON
const data = JSON.parse(json);
// Call the function with the parsed data
const alert = getAlert(data);
console.log(alert);
Additional information
Destructuring assignment
use this function :
function assignJsons(...jsons) {
const convertToObject = jsons.map(json => {
return JSON.parse(json)
});
return JSON.stringify(Object.assign(...convertToObject))
}
//test
console.log(assignJsons(`{"name" : "alex", "family" : "mask"}`, `{"family" : "rejest"}`))
if you want a completely new object
var newJsonObject = JSON.parse('{ "properties":'
+ JSON.stringify (origJson.value.properties) + "}");
or
var newJsonObject={"properties":Object.assign ({}, origJson.value.properties)};

How to parse FractalTransformer with normalizr

I'm trying to use paularmstrong/normalizr on JSON that comes from FractalTransformer and whose nested childs have "data" attribute. Example of JSON:
{
"data": {
"object": "Offer",
"id": "5g6aqocew4qjzl40",
"real_id": 26,
"name": "Random Name",
"created_at": {
"date": "2019-06-18 11:13:08.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"readable_created_at": "1 year ago",
"site": {
"data": {
"object": "Site",
"id": "65zody8vj29vlegd",
"name": "Test Site",
"real_id": 1
}
},
"countries": {
"data": [
{
"object": "Country",
"code": "US",
"name": "United States"
},
{
"object": "Country",
"code": "DE",
"name": "Germany"
}
]
}
},
"meta": {
"include": [
"site",
"countries"
],
"custom": []
}
}
Schemas I use:
export const offerSchema = new schema.Entity('offers')
export const siteSchema = new schema.Entity('sites', {}, {
processStrategy: (value) => {
return { ...value.data }
},
idAttribute: (value) => {
return value.data.id
},
})
export const countrySchema = new schema.Entity('countries')
offerSchema.define({
site: siteSchema,
countries: [countrySchema],
})
Now the issue is that I remove 'data' from the site since it's just one object successfully, but I can't do it in the country case. Whatever I tried with custom processStrategy fails, as country is object that has data which is array (I assume this is where the issue is, going from Entity to Array). And in idAttribute function I always get complete array so can't determine the ID of single entry. So the end result is that the ID of countries is undefined. Any ides?
I actually managed with another approach. I added processStrategy on the parent, 'Offer' in this case, so all 'data' parts get stripped before they reach other child schemas.
const normalizrStripDataOptions = {
processStrategy: (value) => {
const ret = { ...value }
Object.keys(ret).forEach((key) => {
if (ret[key] !== null) {
if (ret[key].data && Array.isArray(ret[key].data)) {
ret[key] = [...ret[key].data]
}
if (ret[key].data && typeof ret[key].data === 'object') {
ret[key] = { ...ret[key].data }
}
}
})
return ret
},
}
export const offerSchema = new schema.Entity('offers', {}, normalizrStripDataOptions)
export const siteSchema = new schema.Entity('sites')
export const countrySchema = new schema.Entity('countries')
offerSchema.define({
site: siteSchema,
countries: [countrySchema],
})

unable to push multiple values/ data to the angular 2-tree

i am having a dynamic json data & 3 buttons "feed data" it contains one set of dynamic data and button 2 " feed another data" it contains another set of dynamic data and button 3 is " Send data" here my issue when ever i press feed data and select option and press send data it is working and after that if i press feed another data and press send data then it is giving error"isSelected is undefined"
error simulation : feed data --> select option --> send data & press feed another data --> select options --> send data then we are getting error
options = {
useCheckbox: true
};
arrayData;
nodes;
data = {
"info": {
"laptop": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"hdd": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
};
dataa = {
"info": {
"mobile": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"storage": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
};
click(tree:TreeModel)
{
this.arrayData= [];
console.log(tree.activeNodes);
let result: any = {};
let rs = [];
// tree.selectedLeafNodeIds = {};
Object.keys(tree.selectedLeafNodeIds).forEach(x=>{
let node:TreeNode=tree.getNodeById(x);
if (node.isSelected)
{
if (node.parent.data.name) //if the node has parent
{
rs.push(node.parent.data.name+'.'+node.data.name);
if (!result[node.parent.data.name]) //If the parent is not in the object
result[node.parent.data.name] = {} //create
result[node.parent.data.name][node.data.name] = true;
}
else {
if (!result[node.data.name]) //If the node is not in the object
result[node.data.name] = {} //create
rs.push(node.data.name);
}
}
})
this.arrayData = rs;
}
feedData(){
const results = Object.keys(this.data.info).map(k => ({
name: k,
children: this.data.info[k].properties
? Object.keys(this.data.info[k].properties).map(kk => ({name: kk}))
: []
}));
this.nodes = results;
}
feedAnother(){
const results = Object.keys(this.dataa.info).map(k => ({
name: k,
children: this.dataa.info[k].properties
? Object.keys(this.dataa.info[k].properties).map(kk => ({name: kk}))
: []
}));
this.nodes = results;
}
when ever i press feed data and press send data then i am able to view the info and lie wise i want to update data i press feed another data then press send data then it needs to get the updated results
below is my stack blitz url : https://stackblitz.com/edit/angular-zapxko
You can simply change nodes object to update the result.
You need to use Async Data method to update nodes. Here are the demo and code from Angular Tree's official documentation.

angularjs: Push is not a function

I have a JSON object like this:
var post = {
"post_id": "1",
"content": "content",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
"likes_count": 0,
"likers": [],
"comments_count": 0,
"commenters": [],
"comments": []
};
And post is passed to the function given below from the front end.
var vm = this;
vm.likePost = function(post) {
var likedPost = post;
vm.userInfo();
likedPost.likers.push(userObject); //Here
myService.postLike(likedPost).success(function(data) {
likedPost.isLiked = true;
likedPost.likes_count++;
vm.posts = data;
});
};
But doing so, I get a JavaScript error saying push is not a function in line likedPost.likers.push(userObject);
And userObject is returned by vm.userInfo() and it looks like this:
vm.userInfo = function() {
myService.getBasicUserInfo().success(function(data) {
vm.currentPost.post_author.id = data.id;
vm.currentPost.post_author.firstName = data.firstName;
vm.currentPost.post_author.lastName = data.lastName;
});
};
and the returned JSON is like this:
{"id":"12","firstName":"Amelia","lastName":"Earheart"}
Can anyone help me figure out the cause of this issue?
UPDATE:
{
"post_id": "12",
"content": "Content is the content that contains the content",
"image": "member-default.jpg",
"created_at": "2016-05-26 14:29:00",
"post_author": {
"id": "12",
"firstName": "Amelia",
"lastName": "Earheart",
},
"isLiked": false,
}
This is what I get upon console.log(likedPost);
The output clearly specifies that likers is not defined. You can put a validation check before using push() method.
//if likedPost.likers is not defined, it will define it as an array
likedPost.likers = likedPost.likers || [];
//Do the push operation
likedPost.likers.push(userObject);
Your likedPost object doesn't have the likers array you expect. Probably you can see if that exists before trying to push.
if (typeof likedPost !== 'undefined')
likedPost.likers.push(userObject);

Covert object to array of combinations/objects

Using lodash or underscore. I'm trying to convert this object:
{
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
}
to this:
var variations = [{
"version": "sport",
"device": "mobile"
}, {
"version": "sport",
"device": "tablet"
}, {
"version": "generic",
"device": "mobile"
}, {
"version": "generic",
"device": "tablet"
}];
What's the best/shortest method to do this?
Not sure with lodash or undesrcore. But with simple jquery i have done this. take a look.
var object={
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
};
var variations=[];
$.each(object.variations.versions, function(i, j) {
$.each(object.variations.devices, function(k, l) {
variations.push({version:j,device:l});
});
});
I think you wanna set object key to new variable name and do combinations of inside object values.
<script type="text/javascript">
//here I created two object keys for more clear
var json ={
"variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
},
"another_variations": {
"versions": ["sport", "generic"],
"devices": ["mobile", "tablet"]
}
};
for(var i in json){
window[i] = []; //here window[variable] will make global variable
ver = Object.keys(json[i])[0];//Object.keys(json[i]) get object keys ~["versions","devices"]
dev = Object.keys(json[i])[1];
window[i].push(
{
[ver]:json[i].versions[0],
[dev]:json[i].devices[0]
},
{
[ver]:json[i].versions[0],
[dev]:json[i].devices[1]
},
{
[ver]:json[i].versions[1],
[dev]:json[i].devices[0]
},
{
[ver]:json[i].versions[1],
[dev]:json[i].devices[1]
});
}
console.log(variations); //here can call object key as a variable name if you
console.log(another_variations);//don't use `window[variable]` in above, this will print undefined error
</script>
Found a solution using: https://gist.github.com/wassname/a882ac3981c8e18d2556
_.mixin({
cartesianProductOf: function(args) {
if (arguments.length > 1) args = _.toArray(arguments);
// strings to arrays of letters
args = _.map(args, opt => typeof opt === 'string' ? _.toArray(opt) : opt)
return _.reduce(args, function(a, b) {
return _.flatten(_.map(a, function(x) {
return _.map(b, function(y) {
return _.concat(x, [y]);
});
}), true);
}, [
[]
]);
},
cartesianProductObj: function(optObj) {
var keys = _.keys(optObj);
var opts = _.values(optObj);
var combs = _.cartesianProductOf(opts);
return _.map(combs, function(comb) {
return _.zipObject(keys, comb);
});
}
});
See working:
https://jsfiddle.net/rickysullivan/5ryf9jsa/

Categories

Resources