AngularJS Array Comparison - javascript

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

Related

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

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

Group and count values in an array

I have an array with objects, like the following.
b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
I want to count how many issues have status close, and how many have backlog. I'd like to save the count in a new array as follows.
a = [
{Name: 'Backlog', count: 1},
{Name: 'close', count: 2}
];
I have tried the following.
b.issues.forEach(function(i) {
var statusName = i.fields.status.name;
if (statusName in a.Name) {
a.count = +1;
} else {
a.push({
Name: statusName,
count: 1
});
}
});
That however doesn't seem to be working. How should I implement this?
This is a perfect opportunity to use Array#reduce. That function will take a function that is applied to all elements of the array in order and can be used to accumulate a value. We can use it to accumulate an object with the various counts in it.
To make things easy, we track the counts in an object as simply {name: count, otherName: otherCount}. For every element, we check if we already have an entry for name. If not, create one with count 0. Otherwise, increment the count. After the reduce, we can map the array of keys, stored as keys of the object, to be in the format described in the question. See below.
var b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
var counts = b.issues.reduce((p, c) => {
var name = c.fields.status.name;
if (!p.hasOwnProperty(name)) {
p[name] = 0;
}
p[name]++;
return p;
}, {});
console.log(counts);
var countsExtended = Object.keys(counts).map(k => {
return {name: k, count: counts[k]}; });
console.log(countsExtended);
.as-console-wrapper {
max-height: 100% !important;
}
Notes.
Array#reduce does not modify the original array.
You can easily modify the function passed to reduce to for example not distinguish between Backlog and backlog by changing
var name = c.fields.status.name;
into
var name = c.fields.status.name.toLowerCase();
for example. More advanced functionality can also easily be implemented.
Using ES6 Arrow functions you can do it with minimum syntax
var b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
var countOfBackLog = b.issues.filter(x => {
return x.fields.status.name === "Backlog"
}).length
var countOfClose = b.issues.filter(x => {
return x.fields.status.name === "close"
}).length
a =[{Name: 'Backlog', count : countOfBackLog}, {Name: 'close', count : countOfClose}]
More about arrow functions here
You can write like this. It is dynamic.
var a = {};
for(var key in b["issues"]){
if(!a.hasOwnProperty(b["issues"][key].fields.status.name)){
a[b["issues"][key].fields.status.name] = 1;
}else{
a[b["issues"][key].fields.status.name] = a[b["issues"][key].fields.status.name]+1;
}
}
var c = [];
for(var key1 in a){
c.push({
name : key1,
count : a[key1]
});
}
Something like this should do the trick. Simply iterate over your data, keep 2 counters with the number of each type of issue, and create the data format you want in the end. Try it live on jsfiddle.
var b = {
"issues": [{
"fields": {
"status": {
"id": "200",
"name": "Backlog"
}
}
}, {
"fields": {
"status": {
"id": "202",
"name": "close"
}
}
}, {
"fields": {
"status": {
"id": "201",
"name": "close"
}
}
}]
};
var data = [];
for(var issue of b.issues){
var entryFound = false;
var tempObj = {
name: issue.fields.status.name,
count: 1
};
for(var item of data){
if(item.name === tempObj.name){
item.count++;
entryFound = true;
break;
}
}
if(!entryFound){
data.push(tempObj);
}
}
console.log(data);

filter result using 2 JSON

This is my saved localstorage,
[{"industry_Id":1,"merchant_id":2}]
I want to filter below result, to get HP.
{
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
}
I thought of using multiple $.each but it have to iterate few times and it's quite redundant.
I would prefer using Javascript for loop, that way you can skip iterating over every object once required element is found.
Without jQuery (using for)
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
With jQuery (using $.each)
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
var arg = [{"industry_Id":1,"merchant_id":2}];
var data = {
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
};
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
console.log(merchant);
document.writeln("<b>Without jQuery:</b><br>");
document.writeln((merchant !== null) ? "Found " + merchant['name'] : "Not found");
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
console.log(merchant_found);
document.writeln("<br><br><b>With jQuery:</b><br>");
document.writeln((merchant_found) ? "Found " + merchant_found['name'] : "Not found");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
selectors.map(function(selector) {
return data.industries.filter(function(industry) {
return industry.id == selector.industry_Id;
})[0].merchant.filter(function(merchant) {
return merchant.id == selector.merchant_id;
})[0].name;
});
// => DEF
If you want "HP", you want industry 2, not industry 1.
.filter(...)[0] is not really optimal. You could use .find(...), but that is not yet universally supported. Or you could use plain old JavaScript and write for loops instead to make it fast. Or you could use objects with ID keys instead of arrays to make lookups faster.
When it comes into a position where collection of data is what you're processing, I suggest you to take a look at underscore.js. It's not optimal choice for the best performance but it does make you code more readable and makes more sense especially when compared with loop.
Say data is a variable which stores your JSON data.
Try this:
// Given this selector criteria
var select = [{"industry_Id":1,"merchant_id":2}];
function filterByCriteria(criteria, data){
var match = [];
_.each(criteria, function(crit){
function matchIndustry(rec){ return rec.id===crit.industry_Id }
function matchMerchant(rec){ return rec.id===crit.merchant_id }
// Filter by industry id
var industry = _.first(_.where(data.industry, matchIndustry));
// Filter by merchant id
var merchant = _.where(industry.merchant, matchMerchant);
_.each(merchant, function addToMatchResult(m){
match.push(m.name);
});
});
return match;
}
var filteredData = filterByCriteria(select, data);
From snippet above, any merchants which match the search criteria will be taken to the match list. Is it more readable to you?
Do you even need numerical id's? Gets super easy when you don't.
/*
{
"industry": {
"oil and gas":{
"merchant": {
"ABC": {
"name": "ABC oil"
},
"DEF": {
"name": "DEF gas"
},
"GHJ" :{
"name": "GHJ oil and gas"
}
}
},
"IT": {
"merchant": {
"Apple" : {
"name": "Apple computers"
},
"HP": {
"name": "Hewlett Packard"
},
"Google": {
"name": "Google. Maw haw haw"
}
}
}
}
}
*/
var data = '{"industry": {"oil and gas":{"merchant": {"ABC": {"name": "ABC oil"},"DEF": {"name": "DEF gas"},"GHJ" :{"name": "GHJ oil and gas"}}},"IT": {"merchant": {"Apple" : {"name": "Apple computers"},"HP": {"name": "Hewlett Packard"},"Google": {"name": "Google. Maw haw haw"}}}}}';
data = JSON.parse(data);
var merchant = data.industry['IT'].merchant['HP'];
alert(merchant.name);
//console.log(merchant.name);

Categories

Resources