How to link nested json relationship values objects with lodash? - javascript

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.

Related

Filter an nested Object with filter and map with JavaScript

I know that this is close to a duplicate but I can't get the code to work. I have an object that I need to filter and I'm currently trying to emulate the accepted as an answer the code at Javascript filtering nested arrays
My data object is:
[{
"project_num": "5R01DA012513-23",
"principal_investigators": [{
"profile_id": 2076451,
"full_name": "PK",
"title": ""
}]
},
{
"project_num": "5R01DK118529-03",
"principal_investigators": [{
"profile_id": 8590844,
"full_name": "HW",
"title": "PROFESSOR, SCIENTIFIC DIRECTOR"
}]
},
{
"project_num": "3R01AA025365-05S1",
"principal_investigators": [{
"profile_id": 8730036,
"full_name": "JJ",
"title": "ASSOCIATE PROFESSOR OF PSYCHIATRY"
}]
},
{
"project_num": "1R01HL163963-01",
"principal_investigators": [{
"profile_id": 2084037,
"full_name": "KH",
"title": "ASSOCIATE PROFESSOR"
},
{
"profile_id": 11309656,
"full_name": "AM",
"title": "RESEARCH ASSISTANT PROFESSOR"
}
]
},
{
"project_num": "5R25HL092611-15",
"principal_investigators": [{
"profile_id": 1886512,
"full_name": "CW",
"title": "P"
}]
}
]
and my JavaScript code is:
let payLoad = 1886512
const result = this.reporterData.map(t => {
const principal_investigators = t.principal_investigators.filter(d =>
d.profile_id === payLoad);
return { ...t,
principal_investigators
};
})
I need to pass in a profile_id as a payload and return the objects that will fill a data table.
The data can be 1000's of items and the principla_investigators can be multiple entries. When I use the code that I have it return all of the objects. Can someone point out my error? Thanks
You can try doing like this:
const result = this.reporterData.filter((t) => {
const principal_investigators = t.principal_investigators.filter((d) => d.profile_id === payLoad)
return (principal_investigators.length > 0)
})
I understand that you want an array with all the investigators matching that ID, right?
Try this:
const result = this.reporterData.reduce((previous, current) => {
if (current.principal_investigators) {
current.principal_investigators.forEach(pi => {
if (pi.profile_id === payLoad) {
previous.push(current)
}
});
}
return previous
}, [])
You can also do for loops with the same result:
const result = [];
for (project of this.reporterData) {
if (project.principal_investigators) {
for (pi of project.principal_investigators) {
if (pi.profile_id == payLoad) {
result.push(pi);
}
}
}
}

Match two object keys and display another object key value in angular 4

i have two objects like this
languages = [
{
"name": "english",
"iso_639_2_code": "eng"
},
{
"name": "esperanto",
"iso_639_2_code": "epo"
},
{
"name": "estonian",
"iso_639_2_code": "est"
}
]
and another is
user = [
{
name: "john",
language: "eng",
country: "US"
}
];
what i have to do is, match iso_639_2_code to language of user then, i have to display Language name not code from languages. basically both are different api, and i have no idea how to do it this in angular 4.
here's a link what i am trying https://stackblitz.com/edit/angular-9k2nff?file=app%2Fapp.component.ts
Use array find:
var languages = [
{"name": "english", "iso_639_2_code": "eng"},
{"name": "esperanto","iso_639_2_code": "epo"},
{"name": "estonian","iso_639_2_code": "est"}
];
var user = [{name: "john",language: "eng",country: "US"}];
var language = languages.find(l => l.iso_639_2_code === user[0].language);
var languageName = language && language.name; // <-- also prevent error when there is no corresponding language found
console.log(languageName);
EDIT:
With multiple user, it will be:
var languages = [
{"name": "english", "iso_639_2_code": "eng"},
{"name": "esperanto","iso_639_2_code": "epo"},
{"name": "estonian","iso_639_2_code": "est"}
];
var users = [
{name: "john",language: "eng",country: "US"},
{name: "john",language: "epo",country: "Esperanto"}
];
var languageNames = languages.filter(
l => users.find(u => l.iso_639_2_code === u.language)
).map(lang => lang.name);
console.log(languageNames);
Use find
var output = languages.find(s => s.iso_639_2_code == user[0].language).name;
Demo
var languages = [{
"name": "english",
"iso_639_2_code": "eng"
},
{
"name": "esperanto",
"iso_639_2_code": "epo"
},
{
"name": "estonian",
"iso_639_2_code": "est"
}
];
var user = [{
name: "john",
language: "eng",
country: "US"
}
];
var output = languages.find(s => s.iso_639_2_code == user[0].language).name;
console.log(output);
Or, if there are multiple users, and you want to find language name for each of them, then use map
var output = user.map(t =>
languages.find(s =>
s.iso_639_2_code == t.language).name);
Demo
var languages = [{
"name": "english",
"iso_639_2_code": "eng"
},
{
"name": "esperanto",
"iso_639_2_code": "epo"
},
{
"name": "estonian",
"iso_639_2_code": "est"
}
];
var user = [{
name: "john",
language: "eng",
country: "US"
}
];
var output = user.map(t =>
languages.find(s =>
s.iso_639_2_code == t.language).name);
console.log(output);
I think here is what you need , for output just run the snippet :
var languages = [
{
"name": "english",
"iso_639_2_code": "eng"
},
{
"name": "esperanto",
"iso_639_2_code": "epo"
},
{
"name": "estonian",
"iso_639_2_code": "est"
}
];
var user = [
{
name: "john",
language: "eng",
country: "US"
}
];
user.map(u => {
let flang = languages.filter(lang => lang.iso_639_2_code === u.language);
if(flang) {
u.language = flang[0].name;
}
return u;
})
console.log(user);
var languages=[
{"name":"english","iso_639_2_code":"eng"},
{"name":"esperanto","iso_639_2_code":"epo"},
{"name":"estonian","iso_639_2_code":"est"}
];
var user=[
{name:"john",language:"eng",country:"US"}
];
var languageFound = languages.find(lang => lang.iso_639_2_code === user[0].language);
if(languageFound){
var languageName = languageFound.name;
console.log(languageName);
}

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

AngularJS Array Comparison

I have got the following array of Usernames
Usernames = [
{
"id": 1,
"userName": "Jack",
"description": "jack is a nice guy",
"userRoleIds": [
1
]
},
{
"id": 2,
"userName": "Caroline",
"description": "Good girl",
"userRoleIds": [
2,3
]
},
{
"id": 3,
"userName": "Smith",
"description": "Smithyyyy",
"userRoleIds": [
1,2
]
}
]
And an array of userRoles.
userRoles = [
{
id: 1,
roleName: "Admin"
},
{
id: 2,
roleName: "Tester"
},
{
id: 3,
roleName: "Developer"
}
]
What i want to get done is first concat the arrays in in Usernames and userRoles to get the following result.
Usernames = [
{
"id": 1,
"userName": "Jack",
"description": "jack is a nice guy",
"userRoleIds": [
{
"id": 1,
"roleName" : "Admin"
}
]
},
{
"id": 2,
"userName": "Caroline",
"description": "Good girl",
"userRoleIds": [
{
"id": 2,
"roleName" : "Tester"
},
{
"id": 3,
"roleName" : "Developer"
}
]
},...
The second thing i want is to be able to filter for the roleName and userName seperated by pipe signs. As in type something in a text box that searches for userName and roleName for example.
if i type
Caroline, Tester
The result will be
result = [
{
"id": 2,
"userName": "Caroline",
"description": "Good girl",
"userRoleIds": [
2,3
]
},
{
"id": 3,
"userName": "Smith",
"description": "Smithyyyy",
"userRoleIds": [
1,2
]
}
]
What is the best practice for achieving this?
Thanks
Here is how I would do it. I prefer using services and take advantage of their functions to keep code clean.
app.service('UserService', function (PermisionsServices) {
var self = {
'list': [],
'load': function (Users) {//Pass your array of Users
angular.forEach(Users, function (user) {
angular.forEach(user.userRoleIds, function (role) {
self.user.userRolesIds.push(PermisionsServices.get(role));
});
self.list.push(user);
});
}, 'get': function (id) {
for (var i = 0; i < self.list.length; i++) {
var obj = self.list[i];
if (obj.id == id) {
return obj;
}
}
}
};
return self;
});
app.service('PermisionsServices', function () {
var self = {
'list': [],
'load': function (permisions) {//Pass your array of permisions
angular.forEach(permisions, function (permision) {
self.list.push(permision);
});
}, 'get': function (id) {
for (var i = 0; i < self.list.length; i++) {
var obj = self.list[i];
if (obj.id == id) {
return obj;
}
}
}
};
return self;
});
Afterwards, you can use it on your controller:
$scope.users=UserService;
And access each of the users as a separate object which can have multiple object permisions.
NOTE: Building the service (populating it) will of course depend on your app logic and controller, you could just easily remove the "load" function and just hardcode the list object by copy and pasting your arrays.
This is the approach I use to load data from API via resource.
Regards
Edit:
For use on the UI, you would just call:
<div ng-repeat='user in users.list'>
{{user.name}} has {{user.permissions}}
</div>
as the object information is already contained within it.
Edit 2:
If you want to search your data, then you can just add a filter like this:
<div ng-repeat='user in users.list | filter: filterList'>
{{user.name}} has {{user.permissions}}
</div>
And then on the controller:
$scope.filterList = function (user) {
if ($scope.filterTextBox) {
return user.name.indexOf($scope.filterTextBox) == 0;
}
return true;
}
Hope this works for you
I would do with pure JS like this. It won't take more than a single assignment line each.
var Usernames = [
{
"id": 1,
"userName": "Jack",
"description": "jack is a nice guy",
"userRoleIds": [
1
]
},
{
"id": 2,
"userName": "Caroline",
"description": "Good girl",
"userRoleIds": [
2,3
]
},
{
"id": 3,
"userName": "Smith",
"description": "Smithyyyy",
"userRoleIds": [
1,2
]
}
],
userRoles = [
{
id: 1,
roleName: "Admin"
},
{
id: 2,
roleName: "Tester"
},
{
id: 3,
roleName: "Developer"
}
],
modified = Usernames.reduce((p,c) => (c.userRoleIds = c.userRoleIds.map(e => e = userRoles.find(f => f.id == e)),p.concat(c)),[]),
query = ["Caroline","Tester"],
filtered = modified.filter(f => query.includes(f.userName) || f.userRoleIds.some(e => query.includes(e.roleName)));
console.log(JSON.stringify(modified,null,2));
console.log(JSON.stringify(filtered,null,2));
You can use lodash to achieve this.
var role = _.find(userRoles, function(role) {
return role.roleName == 'Tester';
});
_.find(Usernames, function(user) {
return user.userName == 'Caroline' || _.indexOf(user.userRoleIds, role.id)>=0;
});

Search deep nested

I am working on a solution where I need to search for an element in a deeply nested JSON by its id. I have been advised to use underscore.js which I am pretty new to.
After reading the documentation http://underscorejs.org/#find , I tried to implement the solution using find, filter and findWhere.
Here is what I tried using find :
var test = {
"menuInputRequestId": 1,
"catalog":[
{
"uid": 1,
"name": "Pizza",
"desc": "Italian cuisine",
"products": [
{
"uid": 3,
"name": "Devilled chicken",
"desc": "chicken pizza",
"prices":[
{
"uid": 7,
"name": "regular",
"price": "$10"
},
{
"uid": 8,
"name": "large",
"price": "$12"
}
]
}
]
},
{
"uid": 2,
"name": "Pasta",
"desc": "Italian cuisine pasta",
"products": [
{
"uid": 4,
"name": "Lasagne",
"desc": "chicken lasage",
"prices":[
{
"uid": 9,
"name": "small",
"price": "$10"
},
{
"uid": 10,
"name": "large",
"price": "$15"
}
]
},
{
"uid": 5,
"name": "Pasta",
"desc": "chicken pasta",
"prices":[
{
"uid": 11,
"name": "small",
"price": "$8"
},
{
"uid": 12,
"name": "large",
"price": "$12"
}
]
}
]
}
]
};
var x = _.find(test, function (item) {
return item.catalog && item.catalog.uid == 1;
});
And a Fiddle http://jsfiddle.net/8hmz0760/
The issue I faced is that these functions check the top level of the structure and not the nested properties thus returning undefined. I tried to use item.catalog && item.catalog.uid == 1; logic as suggested in a similar question Underscore.js - filtering in a nested Json but failed.
How can I find an item by value by searching the whole deeply nested structure?
EDIT:
The following code is the latest i tried. The issue in that is that it directly traverses to prices nested object and tries to find the value. But my requirement is to search for the value in all the layers of the JSON.
var x = _.filter(test, function(evt) {
return _.any(evt.items, function(itm){
return _.any(itm.outcomes, function(prc) {
return prc.uid === 1 ;
});
});
});
Here's a solution which creates an object where the keys are the uids:
var catalogues = test.catalog;
var products = _.flatten(_.pluck(catalogues, 'products'));
var prices = _.flatten(_.pluck(products, 'prices'));
var ids = _.reduce(catalogues.concat(products,prices), function(memo, value){
memo[value.uid] = value;
return memo;
}, {});
var itemWithUid2 = ids[2]
var itemWithUid12 = ids[12]
I dont use underscore.js but you can use this instead
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function find(json,key,value){
var result = [];
for (var property in json)
{
//console.log(property);
if (json.hasOwnProperty(property)) {
if( property == key && json[property] == value)
{
result.push(json);
}
if( isArray(json[property]))
{
for(var child in json[property])
{
//console.log(json[property][child]);
var res = find(json[property][child],key,value);
if(res.length >= 1 ){
result.push(res);}
}
}
}
}
return result;
}
console.log(find(test,"uid",4));

Categories

Resources