I'm a novice using JavaScript syntax and am having trouble adapting any solutions I find to match this.
This is a part of my code:
var arr1 = response;
console.log(arr1);
**This is the response/console logged arr1:
{
"channels": {
"1620184778889x527731420801269760": [
{
"channel": "1620184778889x527731420801269760",
"timetoken": "16204064644032062",
"message": {
"content": "44444444444",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618599897203x154294096401530880": [
{
"channel": "1618599897203x154294096401530880",
"timetoken": "16203351496721278",
"message": {
"content": "fffffffdd",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618613571551x955443898854408200": [
{
"channel": "1618613571551x955443898854408200",
"timetoken": "16204261556065826",
"message": {
"content": "78777",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
]
}
}
Trying to:
I need to get the following data:
1.channel
2.timetoken
3.message > content
4.message > sender
And then I need to dynamically generate an innerHTML property for each channel in the array (the amount of channels will frequently vary).
Something like this for each channel returned (incorrect syntax, just an example):
document.getElementById(channel).innerHTML = sender + ' ' + content + ' ' + timetoken;
I am having difficulty adapting other similar solutions to retrieve the nested array items and use loops. I think I need a loop to go through the channels to retrieve the data and also a loop to generate the innerHTML items, but I have been trying for days and can't get it, I am hoping someone well versed can assist.
Thank you.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
<script>
let dataObject = {
"channels": {
"1620184778889x527731420801269760": [
{
"channel": "1620184778889x527731420801269760",
"timetoken": "16204064644032062",
"message": {
"content": "44444444444",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618599897203x154294096401530880": [
{
"channel": "1618599897203x154294096401530880",
"timetoken": "16203351496721278",
"message": {
"content": "fffffffdd",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618613571551x955443898854408200": [
{
"channel": "1618613571551x955443898854408200",
"timetoken": "16204261556065826",
"message": {
"content": "78777",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
]
}
}
for (let channelName in dataObject.channels) {
for (let item of dataObject.channels[channelName]) {
const channel = item.channel;
const timetoken = item.timetoken;
const content = item.message.content;
const sender = item.message.sender;
const messageType = item.messageType;
const uuid = item.uuid;
// do whatever you want with these data
console.log(channel, timetoken, content, sender, messageType, uuid);
}
}
</script>
Related
I want to loop through all objects values inside object and replace password value with * Restricted * . I want to use recursive way tp loop over all this items
before i was targeting objects that include password value but was thinking that it can appear somewhere else inside the object entry .
this is what i tried
if (entry.requestBody) {
for (const key of Object.keys(entry.requestBody)) {
if (key.toLowerCase().includes("password")) {
entry.requestBody[key] = "***Restricted***"
}
}
if (entry.config._object) {
for (const key of Object.keys(entry.config._object)) {
if (key.toLowerCase().includes("password")) {
entry.config._object[key] = "***Restricted***"
}
}
}
}
{
"requestBody": {
"email": "ror#ror.com",
"password": "asdasdsad"
},
"code": "VALIDATION_ERROR",
"config": {
"isJoi": true,
"name": "ValidationError",
"details": [
{
"message": "\"email\" must be a valid email",
"path": [
"email"
],
"type": "string.email",
"context": {
"value": "ror#ror.com",
"key": "email",
"label": "email"
}
}
],
"_object": {
"email": "ror#ror.com",
"password": "asdasdsad"
},
"_meta": {
"source": "body"
}
}
}
}
"requestBody": {
"email": "ror#ror.com",
"password": "***Restricted***"
}
Instead of recursion, how about using regex for a quick and dirty solution:
var bodyString = JSON.stringify(entry.requestBody);
var fixedBodyString = bodyString.replace(/"password":".*"/g, '"password":"***Restricted***"');
var body = JSON.parse(fixedBodyString );
Working example:
https://playcode.io/353673?tabs=script.js,preview,console
I have result json file with 10000 of lines. inside the one array object there are some unnecessary json object i need remove. I have tried so many ways but it's didn't work for me. herewith the piece line of json file
[
{
"product_id": "easybridge",
"errors": []
},
{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "productization",
"errors": []
},
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
],
"properties": {
"trend": {
"$id": "#/properties/test_ids/items/properties/trend",
"examples": [
true
]
},
"display": {
"$id": "#/properties/test_ids/items/properties/display",
"type": "boolean",
"examples": [
true
]
},
"test_id": {
"$id": "#/properties/test_ids/items/properties/test_id",
"type": "string",
},
"test_name": {
"$id": "#/properties/test_ids/items/properties/test_name",
"type": "string",
},
"maintenance": {
"$id": "#/properties/test_ids/items/properties/maintenance",
"type": "boolean",
]
},
"instance": {
"trend": false,
"display": false,
"test_id": "8597ae3c-e2a9-45c7-b279-bde1710681be",
"test_name": "Equella Pearsonresearch Ping Test",
"nrAlertStatus": "enabled",
"test_locations": [
{
"alert_state": false,
"location_name": "AWS_US_WEST_2",
"location_label": "Portland, OR, USA",
"included_to_health": false
}
],
"included_to_health": false,
"critical_alert_threshold": 60
},
"name": "required",
"argument": "maintenance",
"stack": "instance.test_ids[1] requires property \"maintenance\""
{
"product_id": "easybridge",
"errors": []
},
I just need only
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
}
},
if the errors json array is not empty. i don't need even this json how can i remove "schema" json object and other unnecessary json object and arrays specially "schema" json object using java script or java. please help
Loop through the array, look at each object, and create a new array by copying over the data you need.
For instance, I'm taking it you don't care about an object if its array of errors is empty, and that you don't care about the schema ever:
let newJSON = [];
//Assume the json variable is the parsed JSON file you posted.
for (let element of json) {
//Must have at least one error
if (element.errors.length > 0) {
//Create a new object
let newObj = {
"product_id" : element.product_id,
"errors" : []
};
//Add each errror
for (let error of element.errors) {
//Only copy across what we need
newObj.errors.push({
"property" : error.property,
"message" : error.message
});
}
//Add object to our new array of JSON
newJSON.push(newObj);
}
}
//newJSON is your processed JSON output
The easiest solution can be:
const records = [{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "equella",
"errors": [{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
}
}]
}];
const filteredRecords = records.map((record) => {
record.errors = record.errors.map((error) => {
return {property: error. property, message: error.message};
});
return record;
});
console.log(filteredRecords);
You can use map and destructuring assignment to capture only desired properties
let json = [{"product_id": "equella", "errors": [{"property": "instance.test_ids[1]","message": "requires property \"maintenance\"",'xyz': 'not needed','useless': 'not needed',},{'xyz': 'not needed',}]},]
let op = json.map(({product_id,errors}) =>{
let { property, message } = errors[0]
return { product_id, errors: {property,message}}
})
console.log(op)
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)
I'm working on a little chat application where you can click on different contacts and see / send messages.
I have this users.json file with the contacts:
{
"results":[
{
"gender":"female",
"name":{
"title":"Ms",
"first":"Leonie",
"last":"Otto"
},
"location":{
"street":"3076 raiffeisenstraße",
"city":"meißen",
"state":"sachsen-anhalt",
"postcode":62480
},
"email":"leonie.otto#example.com",
"login":{
"username":"bigwolf465",
"password":"stephane",
"salt":"Ip5qcgs5",
"md5":"fe5df54750c64b7c5d54c92f0cb91f11",
"sha1":"17d255fb64135b5e247a4ef5554557a1d2a8881e",
"sha256":"341d750fce611b853b4f27d485f10ef9f9c3add4de12a7fbf838a1fd2d5168a9"
},
"dob":"1955-01-08 01:03:55",
"registered":"2012-07-07 16:42:10",
"phone":"0265-7006038",
"cell":"0178-0561111",
"id":{
"name":"",
"value":null
},
"picture":{
"large":"https://randomuser.me/api/portraits/women/8.jpg",
"medium":"https://randomuser.me/api/portraits/med/women/8.jpg",
"thumbnail":"https://randomuser.me/api/portraits/thumb/women/8.jpg"
},
"nat":"DE",
"status": "online"
},
{
"gender":"female",
"name":{
"title":"Miss",
"first":"Olive",
"last":"Wright"
},
"location":{
"street":"2912 manukau road",
"city":"timaru",
"state":"otago",
"postcode":30721
},
"email":"olive.wright#example.com",
"login":{
"username":"brownrabbit413",
"password":"derek",
"salt":"gRxy7hHq",
"md5":"dc214ffe467373790c8500abd1ff0f8f",
"sha1":"7b7847e1a9e3b3de081e3eeebf972dc5d2b5527a",
"sha256":"1763dff5c43e1cea431d1ad8c1648c586af9d1e1410001d743078af143ce30b9"
},
"dob":"1982-07-01 12:12:29",
"registered":"2016-03-25 19:15:33",
"phone":"(003)-127-5232",
"cell":"(133)-307-2001",
"id":{
"name":"",
"value":null
},
"picture":{
"large":"assets/img/users/233899238.jpg"
},
"nat":"NZ",
"status": "online"
}
I both put them in a list item where I show their name, username and profile picture. This all works out well.
The next I want is that if I click on the specific contact, it shows all their message history.
So as an example for the contact with the username bigwolf465 I use this json file:
{
"ok": true,
"messages": [
{
"type": "message",
"user": "me",
"text": "Can I have this?",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "No.",
"ts": "1512085950.218404"
},
{
"type": "message",
"user": "me",
"text": "Ah, perhaps I’ve miscommunicated. I’m asking for it because I want it.",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "I understood that, actually.",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "me",
"text": "I think maybe you’re not hearing me. I’d like it because I want it.",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "There's no problem with my hearing. The problem is that your argument is, as the Romans would say:",
"ts": "1512085950.000216"
},
{
"type": "message",
"user": "other",
"text": "Circulus in probando.",
"ts": "1512085950.000216"
}
],
"pin_count": 0
}
I also want to make a list item for these messages, but it doens't seem to work out. This is the JS code I have right now:
const handleContactClick = ({
currentTarget: $li
}) => {
loadContactDetails($li);
};
const loadContactDetails = $li => {
fetch(`./assets/data/messages/${$li.dataset.username}.json`)
.then(r => r.json())
.then(parseContactDetail);
}
const parseContactDetail = messages => {
const $container = document.querySelector(`.messages-list`);
const $li = document.createElement(`li`);
$li.classList.add(`reply`);
$container.appendChild($li);
const $img = document.createElement(`img`);
$img.setAttribute(`src`, `assets/img/me.png`);
$li.appendChild($img);
const $p = document.createElement(`p`);
$p.textContent = `${messages.text}`;
$li.appendChild($p);
}
When I click on the specific contact, it just adds messages with the text "undefined". I don't really know how to fix it, it seems I can't get acces to the JSON file.
Here's the function, fixed:
const parseContactDetail = person => {
const $container = document.querySelector(`.messages-list`);
person.messages.forEach(m => {
const $li = document.createElement(`li`);
$li.classList.add(`reply`);
$container.appendChild($li);
const $img = document.createElement(`img`);
$img.setAttribute(`src`, `assets/img/me.png`);
$li.appendChild($img);
const $p = document.createElement(`p`);
$p.textContent = `${m.text}`;
$li.appendChild($p);
});
}
The function now properly grabs .messages from the passed data object, then loops over the array, creating a <li> for each element.
I'm new to JSON, WebDevelopment, Javascript ...
I have the following JSON file
{
"component": "A",
"status": 0,
"children": [
{
"component": "AA",
"status": 0,
"children": [
{
"component": "AAA",
"status": 0,
"children": []
},
{
"component": "AAB",
"status": 0,
"children": []
}
]
},
{
"component": "AB",
"status": 0,
"children": [
{
"component": "ABA",
"status": 0,
"children": []
},
{
"component": "ABB",
"status": 0,
"children": []
}
]
}
]
}
I need to read it using Javascript/Jquery and then display it. Later on I should develop code for Onclicking a "component A" on a webpage a list of components under it
should be displayed and so on.Depending on the status variable a color is to be assigned to the component displayed ( in the form of an image like a box or something)
I wrote the following code:
<html>
<head>
<title>Demo</title>
</head>
<body>
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var myItems;
$.getJSON('jsonfile.json', function(data) {
JSONArray children = jsonfile.getJSONArray("children");
});
});
</script>
</body>
</html>
Firstly what are the javascript equivalent of java functions for JSON like getJSONArray(), getJSONObject() etc
Secondly any suggestions as to how i go about printing the details using what API's etc.
please show the syntax of $.each in this context
var result = $('#result');
$.each(obj.children, function(i, v){
result.append('<div>' + i + ' - ' + v.component + '</div>');
});
Demo: http://jsfiddle.net/LbJBm/
Documentation: jQuery.each()
var response = JSON.stringify(jsonvar);
response = JSON.parse(response);
response.componet will gives you A and thus you can access hte elements.