How to retrieve value in javascript - javascript

I am returning a json as shown below,
{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}
I am trying to get permissionsid value (it is occurred three places in the JSON), also forgot to mention in the original comment that these alphnumeric values in permissionid and userid are dynamics
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser['permissionId'];
When I am using the following, I am getting Cannot read properties of undefined (reading 'id')
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0].id;
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0];
When I am using the following, I am getting [object%20Object]
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions;
What I am missing here, couldn't find same kind of question

Why stringify and parse?
Anyway, it is more complex than you think
const obj = JSON.parse(str)
console.log(Object.values(obj.entities.users)[0].permissionId)
<script>
const str = `{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}`</script>

I see only 2 places, but in any cases remove this from your code
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
since your response data is parced already automatically
Since you can have several permissions or users , you can not get your data just using [0] or [1] since you don' t know how many users can be in the response. So try this code ( it was tested and working properly)
var permissionIds=[];
Object.values(response.entities.permissions).forEach(element => {
permissionIds.push(element.id)
});
var userIds=[];
Object.values(response.entities.users).forEach(element => {
userIds.push(element.id)
});

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 get attribute value from JSON and write it in file in specific format using node.js

I have a test.json file and It's in below format and I just want to get link value from that file:
Input file from File System:
{
"5cacd1333105": {
"type": "CORR-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"colo": "lvs",
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"calls": null,
"hints": null,
"msgTime": 1574314991130,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"colo": "lvs",
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "0",
"duration": 13368.0,
"calls": null,
"hints": null,
"msgTime": 1574314991162,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"colo": "lvs",
"pool": "msmaster_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "0",
"duration": 15.0,
"calls": null,
"hints": null,
"msgTime": 1574315001625,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
I wanna get the below details from above file:
"https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
"https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j"
"https://www.amazon.qa.pilot.com/Tid-02341723424i842424"
I just want to write into test.js file as below format.
module.exports =
{
fileNames:[
'https://www.amazon.qa.pilot.com/Tid-942342192424j2j234',
'https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j',
'https://www.amazon.qa.pilot.com/Tid-02341723424i842424'
]
}
I don't know how to get those details. Can someone please share me some input on this?
It looks like 5cacd1333105 is a dynamic key, so it might change, and there might be more than one random key like that, so you can use a for... in loop like this to loop each key (prop) in the object:
const d = require('./test.json');
for(let prop in d){
console.log(d[prop])
}
Then you can see that the only relevant property is callSummary array because it contains the link data. Therefore you can loop the array to extract the link data.
for(let prop in d){
const obj = d[prop];
const links = obj.callSummary.map(({link}) => link);
console.log(links);
}
The above uses destructuring inside a .map callback to extract the link string from the objects inside callSummary, returning an array of link strings in links.
However, we still need to take into account the general case of multiple links due to the outer for... in loop.
To combine the links into a single array, you can declare links outside the loops as an empty array, and just push to that array, like this:
const links = [];
for(let prop in d){
const obj = d[prop];
links.push(obj.callSummary.map(({link}) => link));
}
console.log(links);
Finally, you want to write that data into a file. You can use either fs or you could spawn / execute a command line program from within your node.js script. See https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback on how to use fs.writeFile or use child_process e.g.
const d = require('./test.json');
const path = require('path');
const { spawn } = require( 'child_process' );
const links = [];
for(let prop in d){
const obj = d[prop];
links.push(obj.callSummary.map(({link}) => link));
}
const filename = `links-${Date.now()}.js`;
console.log(`Outputting links to ${filename}`);
const echo = spawn( 'echo', [ `
module.exports =
{
fileNames:[
${JSON.stringify(links, false, 2)}
]
}
`, '>', path.join(process.cwd(), filename) ] );
Note the use of backticks. (I didn't test that last bit, but it should work).
You have not shared how you are acquiring this data, but since you added a tag for node.js, I am assuming you are doing this on the server side.
After you make sure the data you received is in JSON format (using JSON.parse) and it is valid, to get the specific fields you require, you can do the following:
let links = [];
let callSummary = json['5cacd1333105'].callSummary
for (let index = 0; index < callSummary.length; index++) {
let call = callSummary[index];
if (call && call.link) {
links.push(call.link);
}
}
After this, you will have al lthe links in the array links and you can do whatever you please with them.
This code have a little risk, but it's work in your situation
const data = {
"5cacd1333105": {
"type": "CORR-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"colo": "lvs",
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"calls": null,
"hints": null,
"msgTime": 1574314991130,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"colo": "lvs",
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "0",
"duration": 13368.0,
"calls": null,
"hints": null,
"msgTime": 1574314991162,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"colo": "lvs",
"pool": "msmaster_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "0",
"duration": 15.0,
"calls": null,
"hints": null,
"msgTime": 1574315001625,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
};
const jsonDAta = JSON.stringify(data,null,null);
const resArr = (jsonDAta.match(/"link":"[^"]+"/g)||[]).map(el=>JSON.parse(`{${el||''}}`).link)
console.log(resArr);

Ηow to extract particular data from JSON inside JSON object

A packet contains the data below but I need to extract the following part:
"data":"YOeNkAAg1wQAYjm/pg==
using JavaScript in node-red. How i can do this?
{
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent
{
\"appeui\":\"01-01-01-01-01-01-01-01\",
\"codr\":\"4/5\",
\"data\":\"YOeNkAAg1wQAYjm/pg==\",
\"datr\":\"SF7BW125\",
\"deveui\":\"39-31-37-33-5b-37-67-19\",
\"freq\":868.29999999999995,
\"gweui\":\"00-80-00-00-a0-00-24-6d\",
\"id\":0,
\"ipol\":true,
\"mhdr\":\"60e78d900020d704\",
\"mic\":\"6239bfa6\",
\"modu\":\"LORA\",
\"ncrc\":true,
\"opts\":\"\",
\"port\":0,
\"powe\":11,
\"rfch\":0,
\"seqn\":1239,
\"size\":13,
\"tmst\":3491353235,
\"twnd\":1
}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var src = {
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent {\"appeui\":\"01-01-01-01-01-01-01-01\",\"codr\":\"4/5\",\"data\":\"YOeNkAAg1wQAYjm/pg==\",\"datr\":\"SF7BW125\",\"deveui\":\"39-31-37-33-5b-37-67-19\",\"freq\":868.29999999999995,\"gweui\":\"00-80-00-00-a0-00-24-6d\",\"id\":0,\"ipol\":true,\"mhdr\":\"60e78d900020d704\",\"mic\":\"6239bfa6\",\"modu\":\"LORA\",\"ncrc\":true,\"opts\":\"\",\"port\":0,\"powe\":11,\"rfch\":0,\"seqn\":1239,\"size\":13,\"tmst\":3491353235,\"twnd\":1}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var payload = src.payload;
payload = JSON.parse(payload.substr(payload.indexOf('{')));
console.log(payload.data);
console.log('"data":"' + payload.data + '"');
var finalResult = {};
finalResult.data = payload.data;
console.log(JSON.stringify(finalResult));
And after removing this strange part JSON could look like this
{
"payload": {
"appeui": "01-01-01-01-01-01-01-01",
"codr": "4/5",
"data": "YOeNkAAg1wQAYjm/pg==",
"datr": "SF7BW125",
"deveui": "39-31-37-33-5b-37-67-19",
"freq": 868.3,
"gweui": "00-80-00-00-a0-00-24-6d",
"id": 0,
"ipol": true,
"mhdr": "60e78d900020d704",
"mic": "6239bfa6",
"modu": "LORA",
"ncrc": true,
"opts": "",
"port": 0,
"powe": 11,
"rfch": 0,
"seqn": 1239,
"size": 13,
"tmst": 3491353235,
"twnd": 1
},
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
If the resualt always look like data...== you can search in the payload for the content between data and == with
var res = array.payload.substring(
response.payload.lastIndexOf("data") + -1,
response.payload.lastIndexOf("==") + 3
);
var response = {
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent {\"appeui\":\"01-01-01-01-01-01-01-01\",\"codr\":\"4/5\",\"data\":\"YOeNkAAg1wQAYjm/pg==\",\"datr\":\"SF7BW125\",\"deveui\":\"39-31-37-33-5b-37-67-19\",\"freq\":868.29999999999995,\"gweui\":\"00-80-00-00-a0-00-24-6d\",\"id\":0,\"ipol\":true,\"mhdr\":\"60e78d900020d704\",\"mic\":\"6239bfa6\",\"modu\":\"LORA\",\"ncrc\":true,\"opts\":\"\",\"port\":0,\"powe\":11,\"rfch\":0,\"seqn\":1239,\"size\":13,\"tmst\":3491353235,\"twnd\":1}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var res = response.payload.substring(
response.payload.lastIndexOf("data") + -1,
response.payload.lastIndexOf("==") + 3
);
console.log(res)

How to do nested loops with object jSON data on nodejs

I'm new use nodejs and mongodb, now I build restful API use nodejs and mongodb. I want use response standard for my API with http://jsonapi.org standard.
I need a suggestion from advance how best way to do it, making my API response like the following JSON data:
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"links": {
"self": "http://example.com/users"
},
"data": [{
"type": "users",
"id": 5b647bb8998248235a0aab3c,
"attributes": {
"username": "luke",
"email": "luke#mail.com",
"password": "password",
"hashpassword":"",
"oldpassword":"$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt":"2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"usertype":"bisnis",
"userstatus":"not aktif"
}
}, {
"type": "users",
"id": 5b647bdf998248235a0aab3d,
"attributes": {
"username": "ken",
"email": "ken#mail.com",
"password": "password",
"hashpassword":"",
"oldpassword":"$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt":"2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"usertype":"bisnis",
"userstatus":"not aktif"
}
}]
}
I have problem with nest iteration when create output as above. This my code:
const UsersModel = mongoose.model('Users');
//...show list user
exports.listUsers = (req, res) => {
UsersModel.find({}, (err, result) => {
if (err) {
res.send({code: 400, failed: 'Error 400'});
}
res.json(result);
});
};
And this is my result JSON:
[
{
"type": "users",
"userstatus": "not aktif",
"_id": "5b647bb8998248235a0aab3c",
"username": "luke",
"email": "luke#mail.com",
"password": "password",
"usertype": "bisnis",
"hashpassword": "$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt": "2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"__v": 0
},
{
"type": "users",
"userstatus": "tidak aktif",
"_id": "5b647bdf998248235a0aab3d",
"username": "ken",
"email": "ken#mail.com",
"password": "password",
"usertype": "personal",
"hashpassword": "$2a$10$hok988mszyIBiXVNjmfifOiPNzXkBRRRynXJS/0qCkvlaBOQs65MO",
"salt": "IiMvtVYVqTpZFXmYQIM4IlS6PJFVZ3kw",
"__v": 0
}
]
And this is my temporary code for my problem.
//...show list user
exports.listUsers = (req, res) => {
UsersModel.find({}, (err, result) => {
if (err) {
res.send({code: 400, failed: 'Error 400'});
}
let listData = [];
for (let key in result) {
let data = {};
let attr = {};
if (result.hasOwnProperty(key)) {
data.type = result[key].type;
data.id = result[key]._id;
for(let i in result[key]) {
if(result[key].hasOwnProperty(i)) {
attr.username = result[key].username;
attr.email = result[key].email;
attr.password = result[key].password;
attr.hashpassword = result[key].hashpassword;
attr.oldpassword = result[key].oldpassword;
attr.salt = result[key].salt;
attr.usertype = result[key].usertype;
attr.userstatus = result[key].userstatus;
}
}
data.attribute = attr;
listData.push(data);
}
}
let collections = {
"meta": {
"copyright": "Copyright 2018 Kotakku Studio and Lab",
"authors": [
"sw. saputra"
]
},
"link": {
"self": req.protocol + '://' + req.get('host') + req.originalUrl
},
"data": listData
}
res.json(collections);
});
};
Please give me suggestion the elegant and the best way to solve my problem if my temporary code is not correct.
Thanks advance.
You need to create a proper mongoose schema according to your requirement and map the res to the schema.
//Schema for users
var UsersSchema = mongoose.Schema({
links: {
self: String
},
data:[{
type: String,
attributes: {
username: String,
.
.
.
}
}]
})
id for each document in an array will be created automatically by MongoDB.
For mongoose schema docs see http://mongoosejs.com/docs/guide.html
You can also check this simple TODO API for reference https://github.com/mkujaggi/node-course-todo-api
In this condition's statement:
if(result[key].hasOwnProperty(i)) {
You should be accessing the i of result[key]:
if(result[key].hasOwnProperty(i)) {
attr.username = result[key][i].username;
attr.email = result[key][i].email;
attr.password = result[key][i].password;
attr.hashpassword = result[key][i].hashpassword;
attr.oldpassword = result[key][i].oldpassword;
attr.salt = result[key][i].salt;
attr.usertype = result[key][i].usertype;
attr.userstatus = result[key][i].userstatus;
}
And you don't need all those .hasOwnProperty checks unless you're modifying native prototypes, which you probably shouldn't. And especially for the Array, it's not necessary if you'd just loop properly with a for instead of a for-in.
exports.listUsers = (req, res) => {
UsersModel.find({}, (err, result) => {
if (err) {
res.send({
code: 400,
failed: 'Error 400'
});
}
let listData = [];
let data = {};
let attr = {};
data.type = result[key].type;
data.id = result[key]._id;
for (let i = 0; i < result[key].length; i++) {
attr.username = result[key][i].username;
attr.email = result[key][i].email;
attr.password = result[key][i].password;
attr.hashpassword = result[key][i].hashpassword;
attr.oldpassword = result[key][i].oldpassword;
attr.salt = result[key][i].salt;
attr.usertype = result[key][i].usertype;
attr.userstatus = result[key][i].userstatus;
}
data.attribute = attr;
listData.push(data);
}
}
let collections = {
"meta": {
"copyright": "Copyright 2018 Kotakku Studio and Lab",
"authors": [
"sw. saputra"
]
},
"link": {
"self": req.protocol + '://' + req.get('host') + req.originalUrl
},
"data": listData
}
res.json(collections);
});
};
I would do something like this with iterating over the keys (this will work dynamically that is even if we don't know key names)
var test=[
{
"type": "users",
"userstatus": "not aktif",
"_id": "5b647bb8998248235a0aab3c",
"username": "luke",
"email": "luke#mail.com",
"password": "password",
"usertype": "bisnis",
"hashpassword": "$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt": "2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"__v": 0
},
{
"type": "users",
"userstatus": "tidak aktif",
"_id": "5b647bdf998248235a0aab3d",
"username": "ken",
"email": "ken#mail.com",
"password": "password",
"usertype": "personal",
"hashpassword": "$2a$10$hok988mszyIBiXVNjmfifOiPNzXkBRRRynXJS/0qCkvlaBOQs65MO",
"salt": "IiMvtVYVqTpZFXmYQIM4IlS6PJFVZ3kw",
"__v": 0
}
]
var listData=[]
test.forEach((obj)=>{
var tempObj={attributes:{}}; //initialize tempObj
Object.keys(obj).forEach((key)=>{
if(key=="_id" || key=="type"){
tempObj[key]=obj[key];
}else{
tempObj.attributes[key]=obj[key];
}
})
listData.push(tempObj);
})
let collections = {
"meta": {
"copyright": "Copyright 2018 Kotakku Studio and Lab",
"authors": [
"sw. saputra"
]
},
"link": {
"self": 'test url'
},
"data": listData
}
console.log(collections)

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);

Categories

Resources