Related
I have below JSON for example where I need to extract all categories Id from the last subcategory if its not empty. For instance: On below JSON I need Ids like mens-apparel-ricky inside last categories object but if this categories was empty I like to extract the last ID like womens-new-arrivals. Basically it should be the list of all these ID's extracted.
Thanks in Advance
"categories": [{
"id": "featured",
"name": "NEW ARRIVALS",
"categories": [{
"id": "featured-new-arrivals",
"name": "New Arrivals",
"categories": [{
"id": "mens-new-arrivals",
"name": "Mens",
"categories": []
}, {
"id": "womens-new-arrivals",
"name": "Womens",
"categories": [{
"id": "mens-apparel-ricky",
"name": "Relaxed",
"categories": []
}, {
"id": "new-arrivals-kids",
"name": "Kids",
"categories": []
}, {
"id": "new-arrivals-accessories",
"name": "Accessories",
"categories": []
}]
}, {
"id": "collections",
"name": "Featured",
"categories": [{
"id": "spring-shop",
"name": "Spring Shop",
"categories": [{
"id": "spring-shop-mens",
"name": "Spring Shop Men's",
"categories": []
}, {
"id": "spring-shop-womens",
"name": "Spring Shop Women's",
"categories": []
}]
}, {
"id": "the-festival-shop",
"name": "The Festival Shop",
"categories": [{
"id": "mens-festival-shop",
"name": "Mens Festival Shop",
"categories": []
}, {
"id": "womens-festival-shop",
"name": "Womens Festival Shop",
"categories": []
}]
}, {
"id": "buddha-collections",
"name": "The Icons Shop",
"categories": [{
"id": "buddha-collections-men",
"name": "Mens",
"categories": []
}, {
"id": "buddha-collections-women",
"name": "Womens",
"categories": []
}]
}, {
"id": "all-black",
"name": "All Black Everything",
"categories": []
}]
}]
}, {
"id": "denim",
"name": "DENIM",
"categories": [{
"id": "denim-view-all",
"name": "Shop All Denim",
"categories": [{
"id": "denim-view-all-mens",
"name": "Mens Denim",
"categories": []
}, {
"id": "denim-view-all-womens",
"name": "Womens Denim",
"categories": []
}, {
"id": "denim-view-all-kids",
"name": "Kids Denim",
"categories": []
}]
}, {
"id": "denim-collections",
"name": "Featured",
"categories": [{
"id": "denim-collections-signature-stitch",
"name": "Big T & Super T Stitch",
"categories": []
}, {
"id": "denim-collections-lighten-up",
"name": "Light Wash Denim",
"categories": []
}, {
"id": "dark-wash-denim",
"name": "Dark Wash Denim",
"categories": []
}]
}]
}]
}
This is what I have tried but being new to coding getting difficult to get list form this complex structure.
var rootCategories = (jsonData.categories);
for (var i=0; i < rootCategories.length; i++)
{
var firstChild = (jsonData.categories[i].categories);
for (var j=0; j < firstChild.length; j++)
{
if ((firstChild[j].categories[j].length != 0)) {
catId = firstChild[j].categories[j].id
console.log(catId);
}
}
}
Below is one possible way to achieve the target.
Code Snippet
// recursive method to get "id"s
const getIds = arr => (
arr.flatMap( // iterate using ".flatMap()" to avoid nesting
({id, categories}) => { // de-structure to directly access "id" & "categories"
if ( // if "categories" is not empty, recurse to next level
Array.isArray(categories) &&
categories.length > 0
) {
return getIds(categories);
} else { // if it is empty, simply return the id
return id;
}
}
)
);
const rawData = {
"categories": [{
"id": "featured",
"name": "NEW ARRIVALS",
"categories": [{
"id": "featured-new-arrivals",
"name": "New Arrivals",
"categories": [{
"id": "mens-new-arrivals",
"name": "Mens",
"categories": []
}, {
"id": "womens-new-arrivals",
"name": "Womens",
"categories": [{
"id": "mens-apparel-ricky",
"name": "Relaxed",
"categories": []
}, {
"id": "new-arrivals-kids",
"name": "Kids",
"categories": []
}, {
"id": "new-arrivals-accessories",
"name": "Accessories",
"categories": []
}]
}, {
"id": "collections",
"name": "Featured",
"categories": [{
"id": "spring-shop",
"name": "Spring Shop",
"categories": [{
"id": "spring-shop-mens",
"name": "Spring Shop Men's",
"categories": []
}, {
"id": "spring-shop-womens",
"name": "Spring Shop Women's",
"categories": []
}]
}, {
"id": "the-festival-shop",
"name": "The Festival Shop",
"categories": [{
"id": "mens-festival-shop",
"name": "Mens Festival Shop",
"categories": []
}, {
"id": "womens-festival-shop",
"name": "Womens Festival Shop",
"categories": []
}]
}, {
"id": "buddha-collections",
"name": "The Icons Shop",
"categories": [{
"id": "buddha-collections-men",
"name": "Mens",
"categories": []
}, {
"id": "buddha-collections-women",
"name": "Womens",
"categories": []
}]
}, {
"id": "all-black",
"name": "All Black Everything",
"categories": []
}]
}]
}, {
"id": "denim",
"name": "DENIM",
"categories": [{
"id": "denim-view-all",
"name": "Shop All Denim",
"categories": [{
"id": "denim-view-all-mens",
"name": "Mens Denim",
"categories": []
}, {
"id": "denim-view-all-womens",
"name": "Womens Denim",
"categories": []
}, {
"id": "denim-view-all-kids",
"name": "Kids Denim",
"categories": []
}]
}, {
"id": "denim-collections",
"name": "Featured",
"categories": [{
"id": "denim-collections-signature-stitch",
"name": "Big T & Super T Stitch",
"categories": []
}, {
"id": "denim-collections-lighten-up",
"name": "Light Wash Denim",
"categories": []
}, {
"id": "dark-wash-denim",
"name": "Dark Wash Denim",
"categories": []
}]
}]
}]
}]
};
console.log(getIds(rawData.categories));
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added in the snippet above.
If you're not afraid of reference loops (shouldn't technically happen in a serialized REST response) you can try recurring function as the simplest way to achieve this
function getIDs(node, isRoot = false) {
if (!node.categories.length) // if I understood your question correctly, you don't want parents to be printed out, otherwise just check for isRoot instead
return isRoot || console.log(node.id);
// with above you won't access non-existent id of the root collection
// because it will stop checking after first true statement
for (const category of categories)
getIDs(category);
}
getIDs(collection, true);
This question already has answers here:
How to groupBy array of objects based on properties in vanilla javascript
(2 answers)
Closed 2 years ago.
I got a json file that contains beer types like this:
{
"type": "Unifiltered",
"name": "Heineken Unfiltered",
"id": "XY",
"brand": "Heineken",
"price": "1250",
"alcohol": "0.04",
"ingredients": [
{
"id": "XY2",
"ratio": "0.15",
"name": "salt"
},
{
"id": "XY3",
"ratio": "0.00",
"name": "sugar"
},
{
"id": "XY4",
"ratio": "0.35",
"name": "barley"
}
],
"isCan": false
},
My task is to group beers by brand:
My friend has a list of all the beers available in his pub, but it’s a huge mess.
He would like to see the beers grouped by brands.
My friend also told you that the Function should return an array of Brand > objects which contain the array of Beers of that Brand.
Example:
[{brand: Heineken, beers: [{...}, ...]}]"
const beers = [{
"type": "Unifiltered",
"name": "Heineken Unfiltered",
"id": "XY",
"brand": "Heineken",
"price": "1250",
"alcohol": "0.04",
"ingredients": [
{
"id": "XY2",
"ratio": "0.15",
"name": "salt"
},
{
"id": "XY3",
"ratio": "0.00",
"name": "sugar"
},
{
"id": "XY4",
"ratio": "0.35",
"name": "barley"
}
],
"isCan": false
},
{
"type": "type",
"name": "name",
"id": "XY",
"brand": "EFES",
"price": "1250",
"alcohol": "0.04",
"ingredients": [
{
"id": "XY2",
"ratio": "0.15",
"name": "salt"
},
{
"id": "XY3",
"ratio": "0.00",
"name": "sugar"
},
{
"id": "XY4",
"ratio": "0.35",
"name": "barley"
}
],
"isCan": false
},
{
"type": "type3",
"name": "name2",
"id": "XY",
"brand": "EFES",
"price": "1250",
"alcohol": "0.04",
"ingredients": [
{
"id": "XY2",
"ratio": "0.15",
"name": "salt"
},
{
"id": "XY3",
"ratio": "0.00",
"name": "sugar"
},
{
"id": "XY4",
"ratio": "0.35",
"name": "barley"
}
],
"isCan": false
}];
var group = beers.reduce((r, a) => {
r[a. brand] = [...r[a. brand] || [], a];
return r;
}, {});
console.log("group", group);
i think its already answered here
let group = beers.reduce((r, a) => {
r[a. brand] = [...r[a. brand] || [], a];
return r;
}, {});
console.log("group", group);
Written in an easily readable format, using array.forEach() in place of shorthand functions:
let beers = [{
"type": "Unifiltered",
"name": "Heineken Unfiltered",
"id": "XY",
"brand": "Heineken",
"price": "1250",
"alcohol": "0.04",
"ingredients": [
{
"id": "XY2",
"ratio": "0.15",
"name": "salt"
},
{
"id": "XY3",
"ratio": "0.00",
"name": "sugar"
},
{
"id": "XY4",
"ratio": "0.35",
"name": "barley"
}
],
"isCan": false
}];
let brands = [];
// Loop over all beers
beers.forEach((beer) => {
// Try to find beer brand in existing list of brand
let brand = brands.filter((brand) => brand.brand === beer.brand)[0];
if(brand) {
// If we find it, push the beer onto the beer property
brand.beers.push(beer);
} else {
// If we don't find it, create a new brand and push it onto brands
brand = {
brand: beer.brand,
beers: [beer]
}
brands.push(brand);
}
});
console.log(brands);
I think Grouping JSON by values can be useful. Using the group_by function and then its is just cleaning up the answer to get what you need.
I'm trying to update the 'positionTitle' field of my graphData object with the 'positionTitle fields of my individualData array.
I need to do it accurately, both sets of data have 'accounts' which both have the same id and fullname for user, I was hoping to try and use this to do the matching.
I want the positionTitle's from the users with same account id or name (whichever is easier) to go into the objects fields.
This is currently what I have:
My Object (that i want to update):
graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
}
My array whose positionTitles I want to take:
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
]
The function I'm currently using, which does take the first positiontitle field of the array:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
positionTitle: IndividualData[0].positions[0].positionTitle
}
}))
}))}))
}))
};
console.log(updatedGraphTable)
console.log('a' + JSON.stringify(updatedGraphTable))
my expected result with the positions updated:
updatedGraphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Managing Director"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Managing Director"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
My current result:
{
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
}, {
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334",
"account": {
"id": "eefe"
},
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}, {
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
}, {
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34",
"account": {
"id": "3546"
},
"position": {
"id": "3999434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546",
"account": {
"id": "3545"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
Sure, the trick would be to first map your data into an object (so you don't have to search over both arrays all the time), and then conditionally set the value (as I saw that your first manager, doesn't really have a matching position).
So to create the dictionary for usage in your later model, you can first do
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
This would then have an object where accountIdToPositionDict["123"] would be Managing Director, and then change the duplicating logic into:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
Where the position would then be set based on the found accountId in the dictionary, or the original title if no match was found
const individualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
];
const graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
};
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
// then use it in the mapping function
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
console.log( updatedGraphTable );
Try the code below.
accountPositions = {};
IndividualData.forEach((data) => {
accountPositions[data.account.id] = data.positions.filter((pos) => {return pos.isPrimary})[0].positionTitle;
});
graphData.engagementAreas.forEach((area) => {
area.engagementTypes.forEach((type) => {
type.engagements.forEach((engagement) => {
engagement.members.forEach((member) => {
if (!accountPositions[member.account.id]) return;
console.log('position updated from ', member.position.positionTitle, 'to', accountPositions[member.account.id]);
member.position.positionTitle = accountPositions[member.account.id];
});
});
});
});
searching the specific value in nested object and returning the updated original object with only searched item using javascript
var people= {
"i": [
{
"country": "Australia",
"list": [
{
"name": "ABC ",
"address": "AB street ",
}
]
},
{
"country": "Brazil",
"list": [
{
"name": "XZ ",
"address": "AB street "
},
...
]
}
]
...
};
I want to search by name.
Using function Object.keys() and breaking the deepest loop when a key === searchedText.
var pages = { "1": [{ "title": "Australia", "list": [{ "key": "Base1", "label": "Base-label", "description": "description" }, { "key": "Base1", "label": "Base-label", "description": "description" } ] }], "2": [{ "title": "Australia", "list": [{ "key": "Base1", "label": "Base-label", "description": "description" }, { "key": "Base1", "label": "Base-label", "description": "description" }, { "key": "Base1", "label": "Base-label", "description": "description" } ] }, { "title": "Netherlands", "list": [{ "key": "Base1", "label": "Base-label", "description": "description" }, { "key": "Base2", "label": "Base-label", "description": "description" }, { "key": "Base1", "label": "Base-label", "description": "description" } ] } ], "3": [{ "title": "Usa", "list": [{ "key": "Base2", "label": "Base-label", "description": "description" }, { "key": "Base1", "label": "Base-label", "description": "description" } ] }, { "title": "Canada", "list": [{ "key": "Base1", "label": "Base-label", "description": "description" }, { "key": "Base1", "label": "Base-label", "description": "description" }, { "key": "Base2", "label": "Base-label", "description": "description" } ] } ]};
var filteredPages = {};
var searchedText = "Base2";
for (var k of Object.keys(pages)) {
for (var o of pages[k]) {
for (var io of o.list) {
if (io.key.toLowerCase().indexOf(searchedText.toLowerCase()) !== -1) {
filteredPages[k] = filteredPages[k] || [];
filteredPages[k].push({
title: o.title,
list: [io]
});
}
}
}
}
console.log(filteredPages)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
I have an array with objects and I am trying to figure out how to filter out a few objects which i dont need their. I am trying to filter it out on the basis of the field code . Below is the code I have tried so far which throws an error a.filter is not a function. What could I be doing in this case. Is filter not the correct way to do it .Thank You.
var chartsArray = [
{
"name": "Total Educated",
"code": "Q035001",
"parent": "EDU_ATTAINMENT",
"value": "9900",
"label": "Total Educated",
"children": []
},
{
"name": "Grade Less than 9",
"code": "Q035003",
"parent": "EDU_ATTAINMENT",
"value": "369",
"label": "Grade 9",
"children": []
},
{
"name": "Grade 9 to 12",
"code": "Q035007",
"parent": "EDU_ATTAINMENT",
"value": "595",
"label": "Grade 9 - 12",
"children": []
},
{
"name": "High School",
"code": "Q035011",
"parent": "EDU_ATTAINMENT",
"value": "1174",
"label": "High School",
"children": []
},
{
"name": "Some College",
"code": "Q035012",
"parent": "EDU_ATTAINMENT",
"value": "1904",
"label": "Some College",
"children": []
},
{
"name": "College Degree - Associate's",
"code": "Q035014",
"parent": "EDU_ATTAINMENT",
"value": "436",
"label": "Associate's",
"children": []
},
{
"name": "College Degree - Bachelor's",
"code": "Q035015",
"parent": "EDU_ATTAINMENT",
"value": "2999",
"label": "Bachelor's",
"children": []
},
{
"name": "College Degree - Master's",
"code": "Q035016",
"parent": "EDU_ATTAINMENT",
"value": "1763",
"label": "Master's",
"children": []
},
{
"name": "College - Professional",
"code": "Q035017",
"parent": "EDU_ATTAINMENT",
"value": "413",
"label": "Professional",
"children": []
},
{
"name": "College Degree - Doctorate",
"code": "Q035018",
"parent": "EDU_ATTAINMENT",
"value": "246",
"label": "Doctorate",
"children": []
},
{
"name": "Enrollments (Total Population)",
"code": "EDU_Enrollments",
"parent": "EDU_ATTAINMENT",
"label": "Enrollments (Total Population)",
"children": [
{
"name": "Nursery school/Preschool",
"code": "Q036003",
"parent": "EDU_Enrollments",
"value": "269",
"label": "Nursery school/Preschool",
"children": []
},
{
"name": "Kindergarten/Elementary school",
"code": "Q036006",
"parent": "EDU_Enrollments",
"value": "1156",
"label": "Kindergarten/Elementary school",
"children": []
},
{
"name": "High School",
"code": "Q036015",
"parent": "EDU_Enrollments",
"value": "539",
"label": "High School",
"children": []
},
{
"name": "College/Graduate /Professional school",
"code": "Q036018",
"parent": "EDU_Enrollments",
"value": "1869",
"label": "College/Graduate /Professional school",
"children": []
},
{
"name": "Not Enrolled",
"code": "Q036024",
"parent": "EDU_Enrollments",
"value": "10380",
"label": "Not Enrolled",
"children": []
}
]
},
{
"name": "Percents",
"code": "PCT_EDU_ATTAINMENT",
"parent": "EDU_ATTAINMENT",
"label": "Percents",
"children": [
{
"name": "% Grade Less than 9",
"code": "XQ035003",
"parent": "PCT_EDU_ATTAINMENT",
"value": "3.7231",
"label": "% Grade 9",
"children": []
},
{
"name": "% Grade 9 to 12",
"code": "XQ035007",
"parent": "PCT_EDU_ATTAINMENT",
"value": "6.0112",
"label": "% Grade 9 - 12",
"children": []
},
{
"name": "% High school",
"code": "XQ035011",
"parent": "PCT_EDU_ATTAINMENT",
"value": "11.8622",
"label": "% High school",
"children": []
},
{
"name": "% Some college",
"code": "XQ035012",
"parent": "PCT_EDU_ATTAINMENT",
"value": "19.2332",
"label": "% Some college",
"children": []
},
{
"name": "% College - Associate",
"code": "XQ035014",
"parent": "PCT_EDU_ATTAINMENT",
"value": "4.4073",
"label": "Associate",
"children": []
},
{
"name": "% College - Bachelors",
"code": "XQ035015",
"parent": "PCT_EDU_ATTAINMENT",
"value": "30.2966",
"label": "Bachelors",
"children": []
},
{
"name": "% College - Masters",
"code": "XQ035016",
"parent": "PCT_EDU_ATTAINMENT",
"value": "17.8096",
"label": "Masters",
"children": []
},
{
"name": "% College - Professional",
"code": "XQ035017",
"parent": "PCT_EDU_ATTAINMENT",
"value": "4.168",
"label": "Professional",
"children": []
},
{
"name": "% College - Doctorate",
"code": "XQ035018",
"parent": "PCT_EDU_ATTAINMENT",
"value": "2.4888",
"label": "Doctorate",
"children": []
}
]
}
];
var el=[
"Q035001",
"PCT_EDU_ATTAINMENT"
];
output = chartsArray = chartsArray.map(a => a.filter(function code(o) {
if (!el.includes(o.code)) {
if (o.children) {
o.children = o.children.filter(code);
}
return true;
}
}));
console.log(output)
chartsArray is an array of objects.
When you do chartsArray.map(a => a.filter(...)),
it means that for each object a in the array, invoke filter.
Which is incorrect since objects don't have a filter method.
It seems you meant to use filter on the array, instead of map:
output = chartsArray = chartsArray.filter(function code(o) {
if (!el.includes(o.code)) {
if (o.children) {
o.children = o.children.filter(code);
}
return true;
}
});
You may use recursion to filter recursively:
const filter = [
"Q035001",
"PCT_EDU_ATTAINMENT"
];
function filterBy(arr, filter){
return arr.filter( obj => {
obj.children = filterBy(obj.children, filter);
return !filter.includes(obj code);
});
}
const output = filterBy(chartsArray, filter);