Normalizr usage for deep nested obj - json

I am trying to use Normalizr for normalize and denormalize object that I am using within my angular ngrx app.
I found almost the solution for it here:https://www.snip2code.com/Snippet/1028240/Deep-nested-tree-normalize-with-normaliz
import {normalize, Schema, arrayOf} from 'normalizr';
var data = [
{
"id": 1,
"name": "О компании",
"children": [
{
"id": 5,
"name": "Руководство",
"children": [
{
"id": 6,
"name": "Генеральный директор",
"children": [
{
"id": 20,
"name": "Зам гендира"
},
{
"id": 8,
"name": "Секретарша"
}
]
},
{
"id": 7,
"name": "Главный бухгалтер",
"children": [
{
"id": 21,
"name": "Зам главбуха"
}
]
}
]
}
]
},
{
"id": 2,
"name": "Вакансии",
"children": [
{
"id": 9,
"name": "Фронтенд-разработчик (JS)"
},
{
"id": 10,
"name": "Бэкэнд-разработчик (Java)"
},
{
"id": 11,
"name": "Оператор ЭВМ"
}
]
}
];
The thing is that many functions from solution below changed and it is little bit hard for me to use same solution with newer release of normalizr. Maybe some of you know how to rewrite below solution into new normalizr?
var node = new Schema('nodes');
node.define({
children: arrayOf(node)
});
var treeSchema = arrayOf(node);
var normalizedData = normalize(data, treeSchema);
console.log(normalizedData);

You're looking at an example using an outdated version of Normalizr. Try reading the docs for new APIs

I did it :)
const node = new schema.Entity('nodes');
node.define({
children: [node]
})
const treeSchema = [node];
const normalizedData = normalize(this.form,treeSchema);

Related

Postman accessing child objects in Json in a Test

I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.

How access the access the whole object by its id

Here we are having two JSON called 1.contacts and 2.workers contacts json is having id called serviceId is nothing but id of workers. when i try to display contacts i want to display workers relevant to that contacts. Here is the stackblits DEMO
Here i have updated stackblitz using sample your data as Array.
https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-ujzzx1
Code:-
let finalResult:any[]=[];
for(let contact of this.contacts){
if(contact.serviceId){
finalResult.push(this.workers.filter(o=>o.id == contact.serviceId));
}
}
console.log("finalResult",finalResult);
You can gather the IDs from the contacts IDs in a map by using map then reduce. After that you iterate over your workers and check in the previously generated map if their serviceId is one of the map's keys.
It looks like this
const contacts = [{
"name": "Jhon Doe",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Peter Parker",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Mark Wood",
"gender": "Male",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
},
{
"name": "Mary Jane",
"gender": "Female",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
}
];
const workers = [
{
"id": "e39f9302-77b3-4c52-a858-adb67651ce86",
"name": "Alfy Odhams"
},
{
"id": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
"name": "Allsun Suttle"
},
{
"id": "ed780d15-428b-4bcd-8a91-bacae8b0b72e",
"name": "Alvinia Ettritch"
},
{
"id": "40665c50-ff74-4e81-b968-e127bdf1fe28",
"name": "Ambrosi Lindenstrauss"
}
];
const contactsIDs = contacts.map(c => c.serviceId).reduce((acc, curr) => {
acc[curr] = true;
return acc;
}, {});
const filteredWorkers = workers.filter(w => w.id in contactsIDs);
console.log(filteredWorkers);

react native json image

I want to print out JSON images as a variable.
This is my local JSON file (JsonData.json):
{
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": [ "1", "2" ],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2",
"name": "soup",
"condition": [ "2", "3" ],
"image": "./appetizer/soup.png"
},
…
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": [ "1" ],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": [ "2", "3" ],
"image": "./main/fish.png"
},
…
]
}
I filtered the name when condition="2". (salad,soup,fish)
This is the code for filtering name:
const newArray1 = [...JsonData["apptizer"], ...JsonData["main"]];
const JsonResult = newArray1.filter(item => {
if(item.condition.indexOf("2") !== -1) return item.name;
});
AND I want to get the image when condition="2".
How can I get them? And How can I print out them?
Do I have to use base64? If so, Can you tell me how to use it?
I saw the explanation, but I can't understand it.
And I imported JSON file this way (I've been correctly using it):
var JsonData = require('./JsonData.json');
You can use below code:
let mainObject = JSON.parse(JSON.stringify(data))
let allKeys = Object.keys(mainObject)
let finalObject = []
allKeys.map((value, index) => {
let array = mainObject[value]
array.map((aryObject, aryIndex) => {
let condition = aryObject['condition']
if (condition.includes('2')) {
finalObject.push(aryObject)
}
})
})
alert(JSON.stringify(finalObject))
You can import data in top of screen:
import { data } from './data';
You can add below text in data.js:
export const data = {
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": ["1"],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2222",
"name": "soup",
"condition": ["2", "3"],
"image": "./appetizer/soup.png"
},
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": ["1"],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": ["21", "3"],
"image": "./main/fish.png"
},
]
}
You can use Object#values to get the arrays corresponding to appetizer and main and then Array#flat to extract the nested objects into a transformed array. Then use the Array#filter (which you are already using) to filter out only the required objects based on your condition and then Array#map to get the name and image values out of every filtered object into an array of objects.
Please consider following snippts
const jsonData = {"appetizer":[{"num":"appetizer1","name":"salad","condition":["1","2"],"image":"./appetizer/salad.png"},{"num":"appetizer2","name":"soup","condition":["2","3"],"image":"./appetizer/soup.png"}],"main":[{"num":"main1","name":"beef","condition":["1"],"image":"./main/beef.png"},{"num":"main2","name":"fish","condition":["2","3"],"image":"./main/fish.png"}]};
const filteredValues = Object.values(jsonData)
.flat()
.filter(o => o.condition.includes('2'))
.map(({name, image}) => ({ name, image }));
console.log(filteredValues);
The output of the above code will be an array of objects having the following structure
[{
"name": SOME_NAME,
"image": SOME_PATH
},
{
"name": SOME_NAME,
"image": SOME_PATH
},
...
]
You can use the above array to retrieve your image path and display it accordingly.
I think you shouldn't be worried about base64 as images are stored locally and path will be sufficient to display the image.
Hope this will help!!!
Side Note: You can avoid the Array#flat part as you are already doing it manually [...JsonData["apptizer"], ...JsonData["main"]] but flat will be handy in case there are more keys in jsonData that need to be considered.

parse json output for primary and secondary hosts from replSetGetStatus

I've used pymongo to connect to mongo replica set and print the status of replica set using json dump. I want to parse this output and display "name" and "stateStr" into a list or array for the user to be able to pick a particular host.Here is my json dump output:
{
{
"replSetGetStatus": {
"date": "2016-10-07T14:21:25",
"members": [
{
"_id": 0,
"health": 1.0,
"name": "xxxxxxxxxxx:27017",
"optime": null,
"optimeDate": "2016-10-07T13:50:11",
"self": true,
"state": 1,
"stateStr": "PRIMARY",
"uptime": 32521
},
{
"_id": 1,
"health": 1.0,
"lastHeartbeat": "2016-10-07T14:21:24",
"lastHeartbeatRecv": "2016-10-07T14:21:24",
"name": "xxxxxxxxxxxx:27017",
"optime": null,
"optimeDate": "2016-10-07T13:50:11",
"pingMs": 0,
"state": 2,
"stateStr": "SECONDARY",
"syncingTo": "xxxxxxxxxxxx:27017",
"uptime": 27297
},
{
"_id": 2,
"health": 1.0,
"lastHeartbeat": "2016-10-07T14:21:24",
"lastHeartbeatRecv": "2016-10-07T14:21:24",
"name": "xxxxxxxxxxxxx:27020",
"pingMs": 0,
"state": 7,
"stateStr": "ARBITER",
"uptime": 32517
}
],
"myState": 1,
"ok": 1.0,
"set": "replica1"
}
}
Please try below Javascript code. It worked for me.
use admin;
var result = rs.status();
var length = result.members.length;
for (var i=0;i<length;i++){
print ("Server Name-" +result.members[i].name);
print ("Server State-" +result.members[i].stateStr);
}

read the json file to output to an highcharts

I came to read the json file to output to an highcharts.
I have a highcharts areagraph whose values are received from json whose format is as follows:
scope.jsondata = [
{
"Name": "A",
"Categories": "03.01",
"Locate": "1",
"Value": 30
},
{
"Name": "A",
"Categories": "03.02",
"Locate": "1",
"Value": 50
},
{
"Name": "A",
"Categories": "03.03",
"Locate": "1",
"Value": 60
},
{
"Name": "A",
"Categories": "03.04",
"Locate": "1",
"Value": 40
},
{
"Name": "A",
"Categories": "03.05",
"Locate": "1",
"Value": 70
}
];
How can I embed those values for my jsondata in angularJS?
scope.render = function (data) {
var target = element.find('#detail-usage-chart'),
firstDate = {
name: scope.jsondata.Name,
data: scope.jsondata.Vaule,
color: '#f48d7f',
type: 'area'
},
tempOption = {
data: [10, 13, 17, 8, 11, 5, 11, 13 ,16, 18, 20, 13, 16, 21, 19],
type: 'spline',
yAxis: 1
}
};
Please provide a suitable way to embed the data from json.
Area chart is expecting a name and an array contaning values in its series:
See here
So all you have to do is just a quick function in order to prepare your data that way. For example:
var scope.readyValues = [];
for(var i=0;i<scope.jsondata.length;i++)
{
scope.readyValues.push(scope.jsondata[i].Value);
}
Next, just configure the series this way:
// .....chart options
series: [{
name: scope.jsondata[0].Name,
data: scope.readyValues
}
If you have multiple Names in your scope.jsondata then you can use jquery map function or you can make an array for each name.
And since you're using angular I recommend you use Highcharts-ng it's easier ;)