How to print normalized data in React/Redux - javascript

I have a data normalized using normalizr:
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
I save entities in reducer and I want to print them on my page.
I can do that like this:
const articles = data.entities.articles;
for (let key in articles) {
console.log( articles[key].author + ', ' + articles[key].title);
}
Is that ok in React/Redux print normalized data in JSX template like this or there is exist a better way?
UPD
I create an application using this example https://github.com/reactjs/redux/tree/master/examples/real-world but I don't understand how there a data from entities printed in JSX templates.
I am confused about a data structure because usually I used arrays but in real-world example a new for me way, where data normalized like this.

To connect your reducer with your view, you need a container. Then in your view, you can do something like in following jsfiddle.
https://jsfiddle.net/madura/g50ocwh2/
var data = {
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: ["324"]
}
},
"users": {
"1": {
"id": "1",
"name": "Paul"
},
"2": {
"id": "2",
"name": "Nicole"
}
},
"comments": {
"324": {
id: "324",
"commenter": "2"
}
}
}
};
console.log(data.entities.articles);
return ( < div > {
Object.keys(data.entities.articles).map(function(key) {
return <p key = {
key
} > {
data.entities.articles[key].title
} < /p>
})
} < /div>);
}
You will get your data as a property to your view after you connect with container. So you can access your data like below in your view.
this.props.data.entities.articles;

Related

Reverse Traverse a hierarchy

I have a hierarchy of objects that contain the parent ID on them. I am adding the parentId to the child object as I parse the json object like this.
public static fromJson(json: any): Ancestry | Ancestry[] {
if (Array.isArray(json)) {
return json.map(Ancestry.fromJson) as Ancestry[];
}
const result = new Ancestry();
const { parents } = json;
parents.forEach(parent => {
parent.parentId = json.id;
});
json.parents = Parent.fromJson(parents);
Object.assign(result, json);
return result;
}
Any thoughts on how to pull out the ancestors if I have a grandchild.id?
The data is on mockaroo curl (Ancestries.json)
As an example, with the following json and a grandchild.id = 5, I would create and array with the follow IDs
['5', '0723', '133', '1']
[{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
},
There is perhaps very many ways to solve this, but in my opinion the easiest way is to simply do a search in the data structure and store the IDs in inverse order of when you find them. This way the output is what you are after.
You could also just reverse the ordering of a different approach.
I would like to note that the json-structure is a bit weird. I would have expected it to simply have nested children arrays, and not have them renamed parent, children, and grandchildren.
let data = [{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
}]
}]
}]
const expectedResults = ['5', '0723', '133', '1']
function traverseInverseResults(inputId, childArray) {
if(!childArray){ return }
for (const parent of childArray) {
if(parent.id === inputId){
return [parent.id]
} else {
let res = traverseInverseResults(inputId, parent.parents || parent.children || parent.grandchildren) // This part is a bit hacky, simply to accommodate the strange JSON structure.
if(res) {
res.push(parent.id)
return res
}
}
}
return
}
let result = traverseInverseResults('5', data)
console.log('results', result)
console.log('Got expected results?', expectedResults.length === result.length && expectedResults.every(function(value, index) { return value === result[index]}))

How do I check if a nested JSON property exists and how many nested properties it has?

This quandary of mine is mainly based on the number of levels of complexity. I'm trying to figure out the JavaScript logic, but the JSON syntax gets complicated too, so any suggestions are appreciated.
I have a JSON file with more or less the following structure, except I have a whole lot more properties of each code type:
[{
"000": {
"code": "A",
"description": "Poor circulation",
},
"001": {
"code": "B",
"description": "Pain in foot",
"subCodes": {
"0": {
"Right":"1",
"Left":"2"
}
}
},
"003": {
"code": "C",
"description": "Exostosis",
"subCodes": {
"0": {
"Ankle":"1",
"Foot":"2",
"Leg":"3",
"Thigh":"4"
}
}
},
}]
The majority of the codes are like code A, and they're to be left alone. However, I need to filter and mark all codes that are like B (that is, having a "subcodes" property AND just the two nested properties "Right" and "Left") to have a '+' next to them; and codes like C (with any subcodes but just "Right" and "Left") to be marked with a '*'.
Assuming I set a variable for the JSON file, how can I filter these? The rest of my code pushes all the descriptions into an array and the codes into an array to feed them into a div, but how can I have an array alongside with just the codes that have subcodes, and then further filter them according to their child values?
Basically, my end goal is to have a div with all the codes like this:
A Poor circulation
B + Pain in foot
C * Exostosis
Should I abandon the array method altogether? Is there a simpler way? I'm using just vanilla JavaScript.
You could just iterate the object's values and check the conditions.
function getValues(data) {
return data.reduce(
(r, o) => r.concat(
Object
.values(o)
.map(({ code, description, subCodes }) => [
code,
subCodes ? 'Left' in subCodes[0] && 'Right' in subCodes[0] ? '+' : '*' : ' ',
description
].join(' '))),
[]
);
}
var data = [{ "000": { code: "A", description: "Poor circulation" }, "001": { code: "B", description: "Pain in foot", subCodes: { "0": { Right: "1", Left: "2" } } }, "003": { code: "C", description: "Exostosis", subCodes: { "0": { Ankle: "1", Foot: "2", Leg: "3", Thigh: "4" } } } }];
console.log(getValues(data));
Quick and dirty reduce hack that fits you end goal of having a div like this
A Poor circulation
B + Pain in foot
C * Exostosis
const data = {
"000": {
"code": "A",
"description": "Poor circulation",
},
"001": {
"code": "B",
"description": "Pain in foot",
"subCodes": {
"0": {
"Right": "1",
"Left": "2"
}
}
},
"003": {
"code": "C",
"description": "Exostosis",
"subCodes": {
"0": {
"Ankle": "1",
"Foot": "2",
"Leg": "3",
"Thigh": "4"
}
}
},
};
let divElement = "<div>\n";
const reduceToDiv = (acc, curr) => {
if (data[curr]["code"]) {
const description = data[curr]["description"];
if (data[curr]["subCodes"]) {
const subCodes = data[curr]["subCodes"][0];
if ("Left" in subCodes && "Right" in subCodes) acc.push("B + " + description);
else acc.push("C * " + description);
} else acc.push("A " + description);
}
return acc;
};
divElement += Object.keys(data).reduce(reduceToDiv, []).join("\n") + "\n</div>";
console.log(divElement);
Your initial input is an array with one element, I don't know if you did it on purpose but this works with your given array:
const input = [{
"000": {
"code": "A",
"description": "Poor circulation",
},
"001": {
"code": "B",
"description": "Pain in foot",
"subCodes": {
"0": {
"Right":"1",
"Left":"2"
}
}
},
"003": {
"code": "C",
"description": "Exostosis",
"subCodes": {
"0": {
"Ankle":"1",
"Foot":"2",
"Leg":"3",
"Thigh":"4"
}
}
},
}];
const filterJson = arr => {
return Object.values(arr[0]).map(el => !el.hasOwnProperty('subCodes') ? `A ${el.description}` : JSON.stringify(el.subCodes).includes('Right') && JSON.stringify(el.subCodes).includes('Left') ? `B +${el.description}` : `C *${el.description}`);
}
console.log(filterJson(input));

How to link nested json relationship values objects with lodash?

i'm trying to assign/merge (really don't know which lodash function) to nested json objects.
I have the following json structure:
{
"sports": [{
"id": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d",
"name": "Soccer",
"slug": "soccer"
}],
"competitions": [{
"id": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe",
"name": "English Premier League",
"sportId": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d"
}],
"contests": [{
"id": "09cee598-7736-4941-b5f5-b26c9da113fc",
"name": "Super Domingo Ingles",
"status": "live",
"competitionId": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe"
}]
}
I want to get one contest object with their relationship linked nested. The expected object is something like this:
{
"id": "09cee598-7736-4941-b5f5-b26c9da113fc",
"name": "Super Domingo Ingles",
"status": "live",
"competition": {
"id": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe",
"name": "English Premier League",
"sport": {
"id": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d",
"name": "Soccer",
"slug": "soccer"
}
}
}]
}
How can I get this kinda of relationship done using lodash ? It can be using pure javascript as well.
You don't need any special assignment operator, or lodash. You just use the =.
ogObject = {
"sports": [{
"id": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d",
"name": "Soccer",
"slug": "soccer"
}],
"competitions": [{
"id": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe",
"name": "English Premier League",
"sportId": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d"
}],
"contests": [{
"id": "09cee598-7736-4941-b5f5-b26c9da113fc",
"name": "Super Domingo Ingles",
"status": "live",
"competitionId": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe"
}]
};
newObject = ogObject.contests[0];
for(var i = 0; i<ogObject.competitions.length;i++){
if(ogObject.competitions[i].id == newObject.competitionId){
newObject.competition = ogObject.competitions[i];
for(var j = 0; j<ogObject.sports.length;j++){
if(ogObject.sports[j].id == newObject.competition.sportId){
newObject.competition.sport = ogObject.sports[j];
break;
}
}
break;
}
}
console.log(newObject)
This might be a builtin from lodash but I doubt it. It would require predefined knowledge of your schema vis-a-vis the relationship between sportId and sports, competitionId and competitions etc...
You really need to show us what you have tried so that we can advise you about the problems that you are facing, otherwise you are just asking for a code writing service ($).
However, in ES2016 you could do this.
'use strict';
const obj = {
sports: [{
id: 'c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d',
name: 'Soccer',
slug: 'soccer',
}],
competitions: [{
id: '4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe',
name: 'English Premier League',
sportId: 'c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d',
}],
contests: [{
id: '09cee598-7736-4941-b5f5-b26c9da113fc',
name: 'Super Domingo Ingles',
status: 'live',
competitionId: '4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe',
}],
};
const transformed = obj.contests.map((contest) => {
const competition = obj.competitions.find(item => item.id === contest.competitionId);
const sport = obj.sports.find(item => item.id === competition.sportId);
const sportLevel = { ...sport };
const competitionLevel = { ...competition, sport: sportLevel };
delete competitionLevel.sportId;
const contestLevel = { ...contest, competition: competitionLevel };
delete contestLevel.competitionId;
return contestLevel;
});
console.log(JSON.stringify(transformed, null, 2));
There's no built-in lodash function that can be used to flatten relational JSON structures. But something like this should work for you:
const sourceJSON = {
"sports": [{
"id": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d",
"name": "Soccer",
"slug": "soccer"
}],
"competitions": [{
"id": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe",
"name": "English Premier League",
"sportId": "c60d0c48-151e-4fa2-bdf8-48cdfa77ad1d"
}],
"contests": [{
"id": "09cee598-7736-4941-b5f5-b26c9da113fc",
"name": "Super Domingo Ingles",
"status": "live",
"competitionId": "4c19ca7c-4d17-46ce-bb4e-e25a4ebe5dbe"
}]
}
function findSport(source, sportId) {
let sport = _.find(source['sports'], {id: sportId});
if(!sport) {
return {};
}
return {
id: sport.id,
name: sport.name,
slug: sport.slug,
}
}
function findCompetition(source, competitionId) {
let competition = _.find(source['competitions'], {id: competitionId});
if(!competition) {
return {};
}
return {
id: competition.id,
name: competition.name,
sport: findSport(source, competition.sportId),
}
}
function flattenContests(source) {
return _.map(source['contests'], (contest) => {
return {
id: contest.id,
name: contest.name,
status: contest.status,
competition: findCompetition(source, contest.competitionId),
}
});
}
console.log(flattenContests(sourceJSON));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Note that considering your original JSON, the flattened object should likely be an array of contests (since contests itself is an array) instead of a single contest object that you're expecting.

Parse array of objects recursively and filter object based on id

i have this array of objects : getCategory (variable)
[
{
"id": "20584",
"name": "Produits de coiffure",
"subCategory": [
{
"id": "20590",
"name": "Coloration cheveux",
"subCategory": [
{
"id": "20591",
"name": "Avec ammoniaque"
},
{
"id": "20595",
"name": "Sans ammoniaque"
},
{
"id": "20596",
"name": "Soin cheveux colorés"
},
{
"id": "20597",
"name": "Protection"
},
{
"id": "20598",
"name": "Nuancier de couleurs"
}
]
},
{
"id": "20593",
"name": "Soins cheveux",
"subCategory": [
{
"id": "20594",
"name": "Shampooing"
},
{
"id": "20599",
"name": "Après-shampooing"
},
{
"id": "20600",
"name": "Masques"
},
and i tried everything i could search in stackoverflow ..
lets say on this array i want to get recursively and object with the specified id .. like 20596 and it should return
{
"id": "20596",
"name": "Soin cheveux colorés"
}
The logic way i am doing is like this :
var getSubcategory = getCategory.filter(function f(obj){
if ('subCategory' in obj) {
return obj.id == '20596' || obj.subCategory.filter(f);
}
else {
return obj.id == '20596';
}
});
dont know what else to do .
Thanks
PS : I dont use it in browser so i cannot use any library . Just serverside with no other library . find dont work so i can only use filter
You need to return the found object.
function find(array, id) {
var result;
array.some(function (object) {
if (object.id === id) {
return result = object;
}
if (object.subCategory) {
return result = find(object.subCategory, id);
}
});
return result;
}
var data = [{ id: "20584", name: "Produits de coiffure", subCategory: [{ id: "20590", name: "Coloration cheveux", subCategory: [{ id: "20591", name: "Avec ammoniaque" }, { id: "20595", name: "Sans ammoniaque" }, { id: "20596", name: "Soin cheveux colorés" }, { id: "20597", name: "Protection" }, { id: "20598", name: "Nuancier de couleurs" }] }, { id: "20593", name: "Soins cheveux", subCategory: [{ id: "20594", name: "Shampooing" }, { id: "20599", name: "Après-shampooing" }, { id: "20600", name: "Masques" }] }] }];
console.log(find(data, '20596'));
console.log(find(data, ''));

Nesting Json Data with jquery

I have this data from a csv file that i have to use in a dependant dropdown with jquery. I can't figure out if it is possible to nest the data i received for what i already have coded.
CSV file
Banco Tarjeta Cuotas Medio_Pago Coeficiente TEA CFT
Santander Visa 1 modulodepago2 1 0.00% 0.00%
Santander Visa 1 nps 1.0262 18.56% 22.84%
Frances Visa 1 modulodepago2 1 0.00% 0.00%
Frances Master 2 nps 1.0262 18.56% 22.84%
My json data comes like this
[{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"modulodepago2",
"coeficiente":"1","tea":"0.00%","cft":"0.00%"},
{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"nps",
"coeficiente":"1.0262","tea":"18.56%","cft":"22.84%"} ...
etc...
Is there a way i can nest this json data like this (+ adding unique names and id's)?
var myJson = {
"banco": [
{
"name": "Santander",
"id": "Santander",
"tarjeta": [
{
"name": "Visa",
"id": "SantanderVisa",
"cuotas": [
{
"name": "1",
"id": "SantanderVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
},
{
"name": "1",
"id": "SantanderVisa2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
},
{
"name": "Frances",
"id": "Frances",
"tarjeta": [
{
"name": "Visa",
"id": "FrancesVisa",
"cuotas": [
{
"name": "1",
"id": "FrancesVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
}
]
},
{
"name": "Master",
"id": "FrancesMaster",
"cuotas": [
{
"name": "2",
"id": "FrancesMaster2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
}
]
}
You will need to group by keys. An easy way to do this is to use Lodash or Underscore.js.
I used Papa Parse to convert the CSV data into JSON.
var csvData = $('#csv-data').text().trim();
var jsonData = Papa.parse(csvData, { delimiter:',', header:true }).data;
var transformedJson = {
banco : _.chain(jsonData)
.groupBy('Banco')
.toPairs()
.map(banco => {
return {
name : banco[0],
id: banco[0],
tarjeta : _.chain(banco[1])
.groupBy('Tarjeta')
.toPairs()
.map(tarjeta => {
return {
name: tarjeta[0],
id: banco[0] + tarjeta[0],
cuotas: _.map(tarjeta[1], cuota => {
return {
name: cuota['Cuotas'],
id: banco[0] + tarjeta[0] + cuota['Cuotas'],
medio_pago: cuota['Medio_Pago'],
coeficiente: cuota['Coeficiente'],
tea: cuota['TEA'],
cft: cuota['CFT']
}
})
};
})
}
}).value()
}
console.log(JSON.stringify(transformedJson, null, 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.4/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<textarea id="csv-data" style="display:none" rows="5" cols="72">
Banco,Tarjeta,Cuotas,Medio_Pago,Coeficiente,TEA,CFT
Santander,Visa,1,modulodepago2,1,0.00%,0.00%
Santander,Visa,1,nps,1.0262,18.56%,22.84%
Frances,Visa,1,modulodepago2,1,0.00%,0.00%
Frances,Master,2,nps,1.0262,18.56%,22.84%
</textarea>
try something like this
you get all medio_pago for the others objects you just use the object name.
I haven't tested it but I'm sure this will work for you.
var Json = ...
$.each(Json, function(i, item) {
alert(myJson[i].banco.tarjeta.cuotas.medio_pago);
});

Categories

Resources