Find the top hierarchy elements from array with parent child relationship - javascript

I am trying to figure out a way to filter out top hierarchical elements from an array, where each object may have a parent-child hierarchy with other elements of the array. Here is what the array looks like:
[
{
"Code": "1A",
"name": "Western Europe",
"hierarchy": "World/",
},
{
"Code": "AT",
"name": "Austria",
"hierarchy": "World/ Western Europe/"
},
{
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
}
]
For this example, the output should be only the first object, because Western Europe is the parent of Austria and the Netherlands.
[
{
"Code": "WO",
"name": "World",
"hierarchy": "",
},
{
"Code": "NA",
"name": "North America",
"hierarchy": "World/",
},
{
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
}
]
Here the output will be World because World is the top Hierarchy.
[
{
"Code": "1A",
"name": "Western Europe",
"hierarchy": "World/",
},
{
"Code": "NA",
"name": "North America",
"hierarchy": "World/",
},
{
"Code": "US",
"name": "United States",
"hierarchy": "World/ North America/",
},
{
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
},
{
"Code": "RS",
"name": "Russia",
"hierarchy": "World/ Eastern Europe/",
},
]
Here, the output should be Western Europe, North America, and Russia (As we don't have Eastern Europe in the list so Russia is at the top of its hierarchy). So, We have to get the top hierarchical elements. I have a function where I can pass the Code and get the hierarchy structure:
getParentChildHierarchy(string Code) { //some code here }
Input: AT
Output: WO>1A>AT
Can you suggest an optimum way to solve this?

One way is to create a Set of all the paths in the data set, i.e. the concatenation of hierarchy with the name (following the same format with slashes and spacing). Then check for which nodes the hierarchy (which references a parent) actually exists in that set. If not, it does not have a parent in the data set:
const data = [
{
"Code": "1A",
"name": "Western Europe",
"hierarchy": "World/",
}, {
"Code": "NA",
"name": "North America",
"hierarchy": "World/",
}, {
"Code": "US",
"name": "United States",
"hierarchy": "World/ North America/",
}, {
"Code": "NL",
"name": "Netherlands",
"hierarchy": "World/ Western Europe/"
}, {
"Code": "RS",
"name": "Russia",
"hierarchy": "World/ Eastern Europe/",
},
];
const keys = new Set(data.map(o => o.hierarchy + " " + o.name + "/"));
const topLevel = data.filter(o => !keys.has(o.hierarchy));
console.log(topLevel);

Related

How to push children array into the parent children array Angular 8

After filtering the data, I am getting below response inside findChildrens function.
Now i am expecting is if this.newRegion have object length more than 1,
than it will merge children of second object inside the parent object children.
For ex - In below Response, i am getting two objects "Africa" and "Europe", So i wanted to merge children of "Europe" inside the parent children of "Africa".
Can anyone please help me to push as my expected output.
findChildrens(){
this.newRegion = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
};
};
Expected Output
this.newRegion = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
},
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
};
Are you looking to do something like
let newRegion = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
let result=newRegion[0];
if(newRegion.length>1){
result.children=result.children.concat(newRegion.slice(1).map(obj=>obj.children).flat())
}
console.log(result)
This function might be what you're looking. But I have to warn you that what you're trying to do is not scalable or representative of code best practices. You might want to edit this code a bit to make it works regardless of how many regions you have.
// It might be preferable to store this in a constant
const REGIONS = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
findChildren() {
if (Object.keys(REGIONS).length > 1) {
const mergedChildren = REGIONS[0].children.concat(REGIONS[1].children);
return ({
...REGIONS[0],
children: mergedChildren
})
} else {
return REGIONS[0];
}
}

how do i delete child element in nested Json Array and rename Id of child element and merge it to parent element? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I've JSON array which is returned after an edit success in react-redux-saga. The record I updated before and after successfull update comes together as an element of JSON array. So, I need to replace the old resort element with the newly updated resort values and also delete the old resort.
Here, in this example, I have updated resortId(id)=15, but my redux-saga returns both-old resort and the updated new resort,clubbed together in a single element in JSON array cuz in the this.props(cuz place part in this id=15 belongs to another saga store).
resortafterupdate=[{
"id": 5,
"name": "The Ananta Udaipur",
"address": "Village Bujhda,Tehsil Girwa",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "string",
"phone": "567890055"
}, {
"id": 10,
"name": "Test",
"address": "Raj Garden road111",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "986289"
}, {
"id": 11,
"name": "bbbbb",
"address": "ggjgjgjh",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "jjkhkhkhk",
"phone": "89789789"
}, {
"id": 12,
"name": "The Classic",
"address": "chandni chowk",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "beverages",
"phone": "687686868"
}, {
"id": 9,
"name": "xyzzzz 56788998877666",
"address": "111111223345566Raj Garden road111",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "afafas asdfasfas",
"phone": "11111111111"
}, {
"id": 13,
"name": "Byculla Navi ln",
"address": "Byculla Navi ln",
"placeId": 3,
"city": "Puducherry",
"state": "Puducherry",
"country": "India",
"details": "beverages",
"phone": "04409"
}, {
"id": 8,
"name": "test address",
"address": "Raj Garden road111",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "afafas asdfasfas",
"phone": "3253453434"
}, {
"id": 7,
"name": "test name",
"address": "test address",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "9862897999"
},
{
"resort": {
"id": 15,
"name": "AAA",
"address": "hjhgkjk",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "jhkhkjhkjhkjh",
"phone": "98789797"
},
"id": 15,
"name": "BBB",
"address": "NewTown",
"details": "jhkhkjhkjhkjh",
"phone": "98789797",
"place": {
"id": 3,
"city": "Puducherry",
"country": "India",
"state": "Puducherry"
}
}
]
How do I delete the child element resort with id=15 as this is old record before the update? And how do I rename the id of "place" to "placeId" and merge the inner parts - placeId,city,state and country to the outer part of the element - name=BBB and Id=15 and address": "NewTown","details": "jhkhkjhkjhkjh","phone": "98789797" to something like this
resortafterupdate=[{
"id": 5,
"name": "The Ananta Udaipur",
"address": "Village Bujhda,Tehsil Girwa",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "string",
"phone": "567890055"
}, {
"id": 10,
"name": "Test",
"address": "Raj Garden road111",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "986289"
}, {
"id": 11,
"name": "bbbbb",
"address": "ggjgjgjh",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "jjkhkhkhk",
"phone": "89789789"
}, {
"id": 12,
"name": "The Classic",
"address": "chandni chowk",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "beverages",
"phone": "687686868"
}, {
"id": 9,
"name": "xyzzzz 56788998877666",
"address": "111111223345566Raj Garden road111",
"placeId": 2,
"city": "Udaipur",
"state": "Rajasthan",
"country": "India",
"details": "afafas asdfasfas",
"phone": "11111111111"
}, {
"id": 13,
"name": "Byculla Navi ln",
"address": "Byculla Navi ln",
"placeId": 3,
"city": "Puducherry",
"state": "Puducherry",
"country": "India",
"details": "beverages",
"phone": "04409"
}, {
"id": 8,
"name": "test address",
"address": "Raj Garden road111",
"placeId": 1,
"city": "Panjim",
"state": "Goa",
"country": "India",
"details": "afafas asdfasfas",
"phone": "3253453434"
}, {
"id": 7,
"name": "test name",
"address": "test address",
"placeId": 4,
"city": "Shillong",
"state": "Meghalaya",
"country": "India",
"details": "afafas asdfasfas",
"phone": "9862897999"
},
{
"id": 15,
"name": "AAA",
"address": "hjhgkjk",
"details": "jhkhkjhkjhkjh",
"phone": "98789797",
"placeId": 3,
"city": "Puducherry",
"country": "India",
"state": "Puducherry"
}
]
I have deleted the "resort" but unable to rename id in place part to placeId and merge it to the outer element.
function deleteKey(obj, keyToDelete) {
Object.keys(obj).forEach(key => {
if (key.toLowerCase() === keyToDelete) {
delete obj[key];
}
value = obj[key];
if (value instanceof Object) {
deleteKey(value, keyToDelete);
}
});
}
deleteKey(resortafterupdate, "resort");
I found a solution to flatten the child props using this answe on this link
Solution
Here's the code I modified according to my needs
function deleteKey(obj, keyToDelete) {
Object.keys(obj).forEach(key => {
if (key.toLowerCase() === keyToDelete) {
delete obj[key];
}
value = obj[key];
if (value instanceof Object) {
deleteKey(value, keyToDelete);
}
});
}
Object.flatten = function(data){
var resultMain = [];
var result = {};
function recurse(cur, prop){
if (Object(cur) !== cur){
result[prop] = cur;
}else if(Array.isArray(cur)){
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop);
if(l == 0)
result[prop] = [];
}else{
var isEmpty = true;
for(var p in cur){
isEmpty = false;
recurse(cur[p], prop==="place" && p==="id"? prop+"Id" : p);
}
if(isEmpty && prop)
result[prop] = {};
}
}
for(var i=0; i<data.length; i++){
result = {};
recurse(data[i], "");
resultMain[i] = result;
}
return resultMain;
}
deleteKey(updateResorts, "resort");
console.log(Object.flatten(newlyaddedResort));

AngularJS filter tree structure recursively by property

I tried multiple things now, but didn't had much success. Let's assume, that I have a list like this:
[
{
"name": "Africa",
"translation": "Afrika",
"someNum": 87207,
"countries": [
{
"name": "Algeria",
"translation": "Algerien",
"someNum": 58020,
"countries": null
},
{
"name": "Morocco",
"translation": "Marokko",
"someNum": 27314,
"countries": null
},
{
"name": "Libya",
"translation": "Lybien",
"someNum": 77788,
"countries": null
},
{
"name": "Somalia",
"translation": "Somalia",
"someNum": 17945,
"countries": null
},
{
"name": "Kenya",
"translation": "Kenia",
"someNum": 12505,
"countries": null
},
{
"name": "Mauritania",
"translation": "Mauretanien",
"someNum": 25787,
"countries": null
},
{
"name": "South Africa",
"translation": "S\u00fcdafrika",
"someNum": 39997,
"countries": null
}
]
},
{
"name": "America",
"translation": "Amerika",
"someNum": 48450,
"countries": [
{
"name": "North America",
"translation": "Nordamerika",
"someNum": 23397,
"countries": [
{
"name": "Canada",
"translation": "Kanada",
"someNum": 58709,
"countries": null
},
{
"name": "USA",
"translation": "USA",
"someNum": 64725,
"countries": [
{
"name": "New York",
"translation": "New York",
"someNum": 50202,
"countries": null
},
{
"name": "California",
"translation": "Kalifornien",
"someNum": 92801,
"countries": [
{
"name": "Los Angeles",
"translation": "Los Angeles",
"someNum": 78283,
"countries": null
},
{
"name": "San Diego",
"translation": "San Diego",
"someNum": 30373,
"countries": null
},
{
"name": "Sacramento",
"translation": "Sacramento",
"someNum": 50721,
"countries": null
},
{
"name": "San Francisco",
"translation": "San Francisco",
"someNum": 65772,
"countries": null
},
{
"name": "Bakersville",
"translation": "Bakersville",
"someNum": 20390,
"countries": null
}
]
},
{
"name": "Lousiana",
"translation": "Lousiana",
"someNum": 26245,
"countries": null
},
{
"name": "Texas",
"translation": "Texas",
"someNum": 57720,
"countries": null
},
{
"name": "Nevada",
"translation": "Nevada",
"someNum": 41399,
"countries": null
},
{
"name": "Montana",
"translation": "Montana",
"someNum": 97221,
"countries": null
},
{
"name": "Virginia",
"translation": "Virginia",
"someNum": 64101,
"countries": null
}
]
}
]
},
{
"name": "Middle America",
"translation": "Mittelamerika",
"someNum": 60813,
"countries": [
{
"name": "Mexico",
"translation": "Mexiko",
"someNum": 97953,
"countries": null
},
{
"name": "Honduras",
"translation": "Honduras",
"someNum": 40591,
"countries": null
},
{
"name": "Guatemala",
"translation": "Guatemala",
"someNum": 41592,
"countries": null
}
]
},
{
"name": "South America",
"translation": "S\u00fcdamerika",
"someNum": 61507,
"countries": null
}
]
},
{
"name": "Asia",
"translation": "Asien",
"someNum": 38179,
"countries": [
{
"name": "China",
"translation": "China",
"someNum": 47266
},
{
"name": "India",
"translation": "Indien",
"someNum": 33424,
"countries": null
},
{
"name": "Malaysia",
"translation": "Malaysia",
"someNum": 38010,
"countries": null
},
{
"name": "Thailand",
"translation": "Thailand",
"someNum": 41356,
"countries": null
},
{
"name": "Vietnam",
"translation": "Vietnam",
"someNum": 79489,
"countries": null
},
{
"name": "Singapore",
"translation": "Singapur",
"someNum": 53176,
"countries": null
},
{
"name": "Indonesia",
"translation": "Indonesien",
"someNum": 89895,
"countries": null
},
{
"name": "Mongolia",
"translation": "Mongolei",
"someNum": 42783,
"countries": null
}
]
},
{
"name": "Europe",
"translation": "Europa",
"someNum": 84723,
"countries": [
{
"name": "North",
"translation": "Nord",
"someNum": 16833,
"countries": [
{
"name": "Norway",
"translation": "Norwegen",
"someNum": 11817,
"countries": null
},
{
"name": "Sweden",
"translation": "Schweden",
"someNum": 38210,
"countries": null
},
{
"name": "Finland",
"translation": "Finnland",
"someNum": 10669,
"countries": null
}
]
},
{
"name": "East",
"translation": "Ost",
"someNum": 28434,
"countries": [
{
"name": "Romania",
"translation": "Rum\u00e4nien",
"someNum": 45122,
"countries": null
},
{
"name": "Bulgaria",
"translation": "Bulgarien",
"countries": null
},
{
"name": "Poland",
"translation": "Polen",
"someNum": 84183,
"countries": null
}
]
},
{
"name": "South",
"translation": "S\u00fcd",
"someNum": 71856,
"countries": [
{
"name": "Italy",
"translation": "Italien",
"someNum": 76406,
"countries": null
},
{
"name": "Greece",
"translation": "Griechenland",
"someNum": 18189,
"countries": null
},
{
"name": "Spain",
"translation": "Spanien",
"someNum": 36148,
"countries": null
}
]
},
{
"name": "West",
"translation": "West",
"someNum": 33487,
"countries": [
{
"name": "France",
"translation": "Frankreich",
"someNum": 72622,
"countries": null
},
{
"name": "England",
"translation": "England",
"someNum": 51927,
"countries": null
},
{
"name": "Portugal",
"translation": "Portugal",
"someNum": 25502,
"countries": null
}
]
}
]
},
{
"name": "Oceania",
"translation": "Ozeanien",
"someNum": 69844,
"countries": [
{
"name": "Australia",
"translation": "Australien",
"someNum": 17211,
"countries": null
},
{
"name": "New Zealand",
"translation": "Neuseeland",
"someNum": 87401,
"countries": null
}
]
},
{
"name": "Arctica",
"translation": "Arktis",
"someNum": 67183,
"countries": null
},
{
"name": "Antarctica",
"translation": "Antarktis",
"someNum": 92518,
"countries": null
}
]
What I try to achieve, is to find all parents and/or children, matching my search criteria while keeping the whole tree intact.
Let's say I am searching for Australia as value of the property name. The expected result would be:
- Oceania
-- Australia
But what I get is
- Oceania
-- Australia
-- New Zealand
Another example: I am searching for Kalifornien as value of the property translation. The expected result would be:
- America
-- North America
--- USA
---- California
----- Bakersville
----- San Diego
----- Sacramento
----- San Francisco
----- Los Angeles
But the actual result is absolutely not, what you'd expect.
So the main problem I am experiencing is, that the original Angular filter doesn't process children correctly.
I have set up a Plunker to demonstrate the problem: https://plnkr.co/edit/3FavpC8XB3hTvT94fZli?p=preview
I can also change the format of the JSON data, if that makes it easier to achieve a proper filtering.
EDIT:
I've had partial success: https://plnkr.co/edit/lDoUK3?p=preview
There's just one problem left. If I search (for example) for California, the objects from the countries property of the object with the name California are missing. So the last item is California (which is good so far), but I also need Bakersville, San Diego & co. under it.
If you want to get the subItems of your selected element in the list, you should add the items whose parent (Or some parent-of-parent) must appear in the list after filtering. To do this, I would recommend you to create a recursive function:
this.getSelectedElementList = function(list, element) {
var result;
for (var i in list) {
if (list[i].name.toLowerCase().indexOf(element) > -1) {
return list[i];
} else {
if (list[i].countries && list[i].countries.length) {
result = this.getSelectedElementList(list[i].countries, element);
if (typeof result !== 'undefined') {
return result;
}
}
}
}
return result;
};
And you can call it inside your preFilter function twice. The first time to get the parent object:
var parentList = _self.getSelectedElementList(_self.listItems, _self.filterQuery.toLowerCase());
And the second one to check that the current item is inside that object:
if (typeof parentList !== 'undefined' && parentList.countries && parentList.countries.length && typeof _self.getSelectedElementList(parentList.countries, item.name.toLowerCase()) !== 'undefined') {
path.push(item);
}
As you are currently filtering only by name, my proposal works this way. I have also updated your Plunkr

Filter data from object inside array typescript

I have an array events as follows,
[{
"_id": "5890b4796166c457ffdee243",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a0325"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee394"
},
"start_time": "2016-11-09T20:00:00-0600",
"id": "1644669702488073"
}, {
"_id": "5890b4796166c457ffdee242",
"description": "Please note that delivery will be delayed on all tickets until Friday January 8, 2016. Please adhere to the published ticket limits, which will be strictly enforced. If you exceed these limits, you may have any or all of your orders and tickets cancelled without notice. Please note: Every person, regardless of age, must have a ticket to be admitted to this event. RAIL RIDE EVENT: When you purchase a ticket to a Talking Stick Resort Arena event, you can ride the METRO LIGHT RAIL at no cost for four hours prior to the event through the end of the transit day.",
"name": "Adele",
"place": {
"name": "Talking Stick Resort Arena",
"location": {
"city": "Phoenix",
"country": "United States",
"latitude": 33.445995372225,
"longitude": -112.07135782626,
"state": "AZ",
"street": "201 E Jefferson St",
"zip": "85004",
"_id": "58992aebf2dbf4369c0a0327"
},
"id": "53475637527",
"_id": "5890b4856166c457ffdee427"
},
"start_time": "2016-11-21T19:30:00-0700",
"id": "905384112862937"
}, {
"_id": "5890b4796166c457ffdee24a",
"description": "Delivery of tickets will be delayed until 12/31/15",
"name": "Adele",
"place": {
"name": "AmericanAirlines Arena",
"location": {
"city": "Miami",
"country": "United States",
"latitude": 25.781236943411,
"longitude": -80.188316709574,
"state": "FL",
"street": "601 Biscayne Blvd",
"zip": "33132",
"_id": "58992aebf2dbf4369c0a0329"
},
"id": "120400119061",
"_id": "5890b4946166c457ffdee464"
},
"start_time": "2016-10-25T19:30:00-0400",
"id": "445046279020601"
}, {
"_id": "5890b4796166c457ffdee244",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a032b"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee354"
},
"start_time": "2016-11-08T20:00:00-0600",
"id": "1662607760654203"
}, {
"_id": "5890b4796166c457ffdee245",
"description": "Delivery will be delayed until Oct 2, 2016.",
"name": "Adele",
"place": {
"name": "American Airlines Center",
"location": {
"city": "Dallas",
"country": "United States",
"latitude": 32.790485550848,
"longitude": -96.810278349053,
"state": "TX",
"street": "2500 Victory Ave",
"zip": "75219",
"_id": "58992aebf2dbf4369c0a032d"
},
"id": "26606856232",
"_id": "5890b47b6166c457ffdee2e4"
},
"start_time": "2016-11-02T20:00:00-0500",
"id": "649884741817020"
}]
How to get all the city from the above json using typescript?
i have tried this,
this.eventsFiltered = this.events.filter(
book => book.place.location.city);
try this:
this.eventsFiltered = this.events.map(
book => book.place.location.city);
EDIT
i want to filter the events which has speficic places?
let events = [{
"_id": "5890b4796166c457ffdee243",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a0325"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee394"
},
"start_time": "2016-11-09T20:00:00-0600",
"id": "1644669702488073"
}, {
"_id": "5890b4796166c457ffdee242",
"description": "Please note that delivery will be delayed on all tickets until Friday January 8, 2016. Please adhere to the published ticket limits, which will be strictly enforced. If you exceed these limits, you may have any or all of your orders and tickets cancelled without notice. Please note: Every person, regardless of age, must have a ticket to be admitted to this event. RAIL RIDE EVENT: When you purchase a ticket to a Talking Stick Resort Arena event, you can ride the METRO LIGHT RAIL at no cost for four hours prior to the event through the end of the transit day.",
"name": "Adele",
"place": {
"name": "Talking Stick Resort Arena",
"location": {
"city": "Phoenix",
"country": "United States",
"latitude": 33.445995372225,
"longitude": -112.07135782626,
"state": "AZ",
"street": "201 E Jefferson St",
"zip": "85004",
"_id": "58992aebf2dbf4369c0a0327"
},
"id": "53475637527",
"_id": "5890b4856166c457ffdee427"
},
"start_time": "2016-11-21T19:30:00-0700",
"id": "905384112862937"
}, {
"_id": "5890b4796166c457ffdee24a",
"description": "Delivery of tickets will be delayed until 12/31/15",
"name": "Adele",
"place": {
"name": "AmericanAirlines Arena",
"location": {
"city": "Miami",
"country": "United States",
"latitude": 25.781236943411,
"longitude": -80.188316709574,
"state": "FL",
"street": "601 Biscayne Blvd",
"zip": "33132",
"_id": "58992aebf2dbf4369c0a0329"
},
"id": "120400119061",
"_id": "5890b4946166c457ffdee464"
},
"start_time": "2016-10-25T19:30:00-0400",
"id": "445046279020601"
}, {
"_id": "5890b4796166c457ffdee244",
"description": "Adele",
"name": "Adele",
"place": {
"name": "Houston Toyota Center",
"location": {
"city": "Houston",
"country": "United States",
"latitude": 29.751054939716,
"longitude": -95.362142762854,
"state": "TX",
"street": "1510 Polk St",
"zip": "77002",
"_id": "58992aebf2dbf4369c0a032b"
},
"id": "200866860532",
"_id": "5890b47c6166c457ffdee354"
},
"start_time": "2016-11-08T20:00:00-0600",
"id": "1662607760654203"
}, {
"_id": "5890b4796166c457ffdee245",
"description": "Delivery will be delayed until Oct 2, 2016.",
"name": "Adele",
"place": {
"name": "American Airlines Center",
"location": {
"city": "Dallas",
"country": "United States",
"latitude": 32.790485550848,
"longitude": -96.810278349053,
"state": "TX",
"street": "2500 Victory Ave",
"zip": "75219",
"_id": "58992aebf2dbf4369c0a032d"
},
"id": "26606856232",
"_id": "5890b47b6166c457ffdee2e4"
},
"start_time": "2016-11-02T20:00:00-0500",
"id": "649884741817020"
}];
let eventsFiltered = events.map(
book => book.place.location.city);
console.log(eventsFiltered);
let city = 'Houston';
let eventsCt = events.filter(book => book.place.location.city == city);
console.log('2nd question');
console.log(eventsCt);
EDIT 2
i have a field named "parent" which is an array of string. i already
have a string named "12344" which is a part of array parent. how do i
check if the events.parent cotains this string and filter those
objects
let p = '1234';
let eventsF = events.filter(book => book.parent && Array.isArray(book.parent)&& book.parent.indexOf(p) !== -1);
Filter used for filter records with where conditions. In your case you want transform data and you just want a array of city from an array of object. So in this case use map instance of filter
Example
this.cityList = this.events.map(book => book.place.location.city);

Parsing JsonP with Javascript

I am trying to parse JSON data like this:
var baseUrl = 'https://api.themoviedb.org/3/movie/'
var movieID = '550'
var detailUrl = '&append_to_response=releases,trailers,credits&callback=?'
var apiKey = '?api_key=Removed_For_Privacy'
The above url with the api key include returns this result:
?({
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": "10.2188172784825",
"poster_path": "/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
},
{
"name": "Fox 2000 Pictures",
"id": 711
},
{
"name": "Regency Enterprises",
"id": 508
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-14",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if you've never been in a fight?",
"title": "Fight Club",
"vote_average": 7.6,
"vote_count": 2787,
"releases": {
"countries": [
{
"iso_3166_1": "US",
"certification": "R",
"release_date": "1999-10-14"
},
{
"iso_3166_1": "DE",
"certification": "18",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "GB",
"certification": "18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "FR",
"certification": "16",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "TR",
"certification": "",
"release_date": "1999-12-10"
},
{
"iso_3166_1": "BR",
"certification": "feibris",
"release_date": "1999-07-12"
},
{
"iso_3166_1": "FI",
"certification": "K-18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "BG",
"certification": "c",
"release_date": "2012-08-28"
},
{
"iso_3166_1": "IT",
"certification": "VM14",
"release_date": "1999-10-29"
}
]
},
"trailers": {
"quicktime": [],
"youtube": [
{
"name": "Trailer 1",
"size": "HD",
"source": "SUXWAEX2jlg",
"type": "Trailer"
}
]
},
"credits": {
"cast": [
{
"id": 819,
"name": "Edward Norton",
"character": "The Narrator",
"order": 0,
"cast_id": 4,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
},
{
"id": 287,
"name": "Brad Pitt",
"character": "Tyler Durden",
"order": 1,
"cast_id": 5,
"profile_path": "/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
},
{
"id": 1283,
"name": "Helena Bonham Carter",
"character": "Marla Singer",
"order": 2,
"cast_id": 6,
"profile_path": "/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
},
{
"id": 7470,
"name": "Meat Loaf",
"character": "Robert 'Bob' Paulson",
"order": 3,
"cast_id": 7,
"profile_path": "/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
},
{
"id": 7499,
"name": "Jared Leto",
"character": "Angel Face",
"order": 4,
"cast_id": 30,
"profile_path": "/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
},
{
"id": 7471,
"name": "Zach Grenier",
"character": "Richard Chesler",
"order": 5,
"cast_id": 31,
"profile_path": "/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
},
{
"id": 7497,
"name": "Holt McCallany",
"character": "The Mechanic",
"order": 6,
"cast_id": 32,
"profile_path": "/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
},
{
"id": 7498,
"name": "Eion Bailey",
"character": "Ricky",
"order": 7,
"cast_id": 33,
"profile_path": "/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"
}
],
"crew": [
{
"id": 7469,
"name": "Jim Uhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "Ross Grayson Bell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "Ceán Chaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "Art Linson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "John King",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7478,
"name": "Michael Simpson",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7479,
"name": "Jeff Cronenweth",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 7480,
"name": "James Haygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "Laray Mayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "Alex McDowell",
"department": "Art",
"job": "Production Design",
"profile_path": null
},
{
"id": 7763,
"name": "Ren Klyce",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7764,
"name": "Richard Hymns",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7467,
"name": "David Fincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "Chuck Palahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
})
I use this to parse it, however i have no luck
$(document).ready(function() {
$.ajax({
url: baseUrl + movieID +apiKey +detailUrl,
dataType: "jsonp",
success: getGenres,
});
});
function getGenres(data) {
var entries = data
genre = 0,
genre_list = '';
for (genre = 0; genre < entries.genres.name.length; genre++) {
genre_list.push(entries.genres.name[genre]);
}
document.getElementById('Genres').innerHTML = genre_list.join(', ');
Please Help
entries.genres is an Array. It has no .name property. You should be getting an error in your browser's developer console for accessing .length of undefined.
{
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
...
}
So you need to iterate entries.genres, then push the .name of the current genre if that's what you want.
for (genre = 0; genre < entries.genres.length; genre++) {
genre_list.push(entries.genres[genre].name);
}
On a different note, you have two implicit globals.
var entries = data
genre = 0,
genre_list = '';
By forgetting the comma after var entries = data, the next two lines will implicitly create global variables since they're not part of the var statement.
That's why I always use leading commas for variable declarations. Makes it obvious when a comma is missing.
var entries = data
, genre = 0
, genre_list = '';
test.php
<?php
echo 'getGenres({
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": "10.2188172784825",
"poster_path": "/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
},
{
"name": "Fox 2000 Pictures",
"id": 711
},
{
"name": "Regency Enterprises",
"id": 508
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-14",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if youve never been in a fight?",
"title": "Fight Club",
"vote_average": 7.6,
"vote_count": 2787,
"releases": {
"countries": [
{
"iso_3166_1": "US",
"certification": "R",
"release_date": "1999-10-14"
},
{
"iso_3166_1": "DE",
"certification": "18",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "GB",
"certification": "18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "FR",
"certification": "16",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "TR",
"certification": "",
"release_date": "1999-12-10"
},
{
"iso_3166_1": "BR",
"certification": "feibris",
"release_date": "1999-07-12"
},
{
"iso_3166_1": "FI",
"certification": "K-18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "BG",
"certification": "c",
"release_date": "2012-08-28"
},
{
"iso_3166_1": "IT",
"certification": "VM14",
"release_date": "1999-10-29"
}
]
},
"trailers": {
"quicktime": [],
"youtube": [
{
"name": "Trailer 1",
"size": "HD",
"source": "SUXWAEX2jlg",
"type": "Trailer"
}
]
},
"credits": {
"cast": [
{
"id": 819,
"name": "Edward Norton",
"character": "The Narrator",
"order": 0,
"cast_id": 4,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
},
{
"id": 287,
"name": "Brad Pitt",
"character": "Tyler Durden",
"order": 1,
"cast_id": 5,
"profile_path": "/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
},
{
"id": 1283,
"name": "Helena Bonham Carter",
"character": "Marla Singer",
"order": 2,
"cast_id": 6,
"profile_path": "/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
},
{
"id": 7470,
"name": "Meat Loaf",
"character": "Robert Bob Paulson",
"order": 3,
"cast_id": 7,
"profile_path": "/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
},
{
"id": 7499,
"name": "Jared Leto",
"character": "Angel Face",
"order": 4,
"cast_id": 30,
"profile_path": "/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
},
{
"id": 7471,
"name": "Zach Grenier",
"character": "Richard Chesler",
"order": 5,
"cast_id": 31,
"profile_path": "/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
},
{
"id": 7497,
"name": "Holt McCallany",
"character": "The Mechanic",
"order": 6,
"cast_id": 32,
"profile_path": "/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
},
{
"id": 7498,
"name": "Eion Bailey",
"character": "Ricky",
"order": 7,
"cast_id": 33,
"profile_path": "/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"
}
],
"crew": [
{
"id": 7469,
"name": "Jim Uhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "Ross Grayson Bell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "Ceán Chaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "Art Linson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "John King",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7478,
"name": "Michael Simpson",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7479,
"name": "Jeff Cronenweth",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 7480,
"name": "James Haygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "Laray Mayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "Alex McDowell",
"department": "Art",
"job": "Production Design",
"profile_path": null
},
{
"id": 7763,
"name": "Ren Klyce",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7764,
"name": "Richard Hymns",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7467,
"name": "David Fincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "Chuck Palahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
})';
exit;
?>
javascript code:
<script language="javascript">
jq(document).ready(function() {
jq.ajax({
url: 'test.php',
dataType: "jsonp",
}); });
function getGenres(data){
alert(data.genres.length);
}
</script>
Your json response contains single quotes (') example 'bob' and you've which are not standard, so replace then by \' and then parse your json response.
For reference check jQuery single quote in JSON response
Remove ?( and ) from the starting and end of json response and also remove ' from them and check
var obj = jQuery.parseJSON( '{"adult":false,"backdrop_path":"/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}],"homepage":"","id":550,"imdb_id":"tt0137523","original_title":"Fight Club","overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground fight clubs forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.","popularity":"10.2188172784825","poster_path":"/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg","production_companies":[{"name":"20th Century Fox","id":25},{"name":"Fox 2000 Pictures","id":711},{"name":"Regency Enterprises","id":508}],"production_countries":[{"iso_3166_1":"DE","name":"Germany"},{"iso_3166_1":"US","name":"United States of America"}],"release_date":"1999-10-14","revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"English"}],"status":"Released","tagline":"How much can you know about yourself if youve never been in a fight?","title":"Fight Club","vote_average":7.6,"vote_count":2787,"releases":{"countries":[{"iso_3166_1":"US","certification":"R","release_date":"1999-10-14"},{"iso_3166_1":"DE","certification":"18","release_date":"1999-11-10"},{"iso_3166_1":"GB","certification":"18","release_date":"1999-11-12"},{"iso_3166_1":"FR","certification":"16","release_date":"1999-11-10"},{"iso_3166_1":"TR","certification":"","release_date":"1999-12-10"},{"iso_3166_1":"BR","certification":"feibris","release_date":"1999-07-12"},{"iso_3166_1":"FI","certification":"K-18","release_date":"1999-11-12"},{"iso_3166_1":"BG","certification":"c","release_date":"2012-08-28"},{"iso_3166_1":"IT","certification":"VM14","release_date":"1999-10-29"}]},"trailers":{"quicktime":[],"youtube":[{"name":"Trailer 1","size":"HD","source":"SUXWAEX2jlg","type":"Trailer"}]},"credits":{"cast":[{"id":819,"name":"Edward Norton","character":"The Narrator","order":0,"cast_id":4,"profile_path":"/iUiePUAQKN4GY6jorH9m23cbVli.jpg"},{"id":287,"name":"Brad Pitt","character":"Tyler Durden","order":1,"cast_id":5,"profile_path":"/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"},{"id":1283,"name":"Helena Bonham Carter","character":"Marla Singer","order":2,"cast_id":6,"profile_path":"/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"},{"id":7470,"name":"Meat Loaf","character":"Robert Bob Paulson","order":3,"cast_id":7,"profile_path":"/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"},{"id":7499,"name":"Jared Leto","character":"Angel Face","order":4,"cast_id":30,"profile_path":"/msugySeTCyCmlRWtyB6sMixTQYY.jpg"},{"id":7471,"name":"Zach Grenier","character":"Richard Chesler","order":5,"cast_id":31,"profile_path":"/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"},{"id":7497,"name":"Holt McCallany","character":"The Mechanic","order":6,"cast_id":32,"profile_path":"/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"},{"id":7498,"name":"Eion Bailey","character":"Ricky","order":7,"cast_id":33,"profile_path":"/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"}],"crew":[{"id":7469,"name":"Jim Uhls","department":"Writing","job":"Author","profile_path":null},{"id":7474,"name":"Ross Grayson Bell","department":"Production","job":"Producer","profile_path":null},{"id":7475,"name":"Ceán Chaffin","department":"Production","job":"Producer","profile_path":null},{"id":1254,"name":"Art Linson","department":"Production","job":"Producer","profile_path":"/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"},{"id":7477,"name":"John King","department":"Sound","job":"Original Music Composer","profile_path":null},{"id":7478,"name":"Michael Simpson","department":"Sound","job":"Original Music Composer","profile_path":null},{"id":7479,"name":"Jeff Cronenweth","department":"Camera","job":"Director of Photography","profile_path":null},{"id":7480,"name":"James Haygood","department":"Editing","job":"Editor","profile_path":null},{"id":7481,"name":"Laray Mayfield","department":"Production","job":"Casting","profile_path":null},{"id":1303,"name":"Alex McDowell","department":"Art","job":"Production Design","profile_path":null},{"id":7763,"name":"Ren Klyce","department":"Sound","job":"Sound Editor","profile_path":null},{"id":7764,"name":"Richard Hymns","department":"Sound","job":"Sound Editor","profile_path":null},{"id":7467,"name":"David Fincher","department":"Directing","job":"Director","profile_path":"/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"},{"id":7468,"name":"Chuck Palahniuk","department":"Writing","job":"Novel","profile_path":"/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"}]}}' );
alert( obj.genres.length );
alert messages showing 3, so your json response is not valid

Categories