JS filter array by array within - javascript

I have an array as following
[{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
},
{
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage2.jpg",
"ratings": "1",
"price": 700,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
],
And when the user select a certain menu it needs to be filtered through it,
Each dish objects may have more than one menu_id,
i attempted using array.filter but i am having trouble figuring out how to filter from the Dish array through the sub array within.
the code i attempted (filterBy = 4)
let result = data.filter(function(row) {
row.restaurant_dish_menus.filter(function(i) {
return i.menu_id == filterBy;
});
});
console.log(result) gives me an empty array.
if filterBy is = 4 the expected output is
{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
And if it filterBy is 3 then both objects should be the output

how about this
var data = [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}];
var result = data.filter(function(m) {
return m.restaurant_dish_menus.some(function(d) {
return d.menu_id === 4;
});
})

.filter expects the function passed to return a boolean. In your case, the function returns nothing (or undefined) which is always falsy.
One option is to use .find in the nested filter, and return a boolean depending on whether the result is undefined.
Here's a snippet.
let data = [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}, {
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [{
"id": 1,
"res_dish_id": 1318,
"menu_id": 6,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 5,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}, ]
let filterBy = 4;
let result = data.filter(function(row) {
return row.restaurant_dish_menus.find(function(i) {
return i.menu_id == filterBy;
}) !== undefined;
});
console.log(result);

You can use "filter" as below
var data = [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
},
{
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage2.jpg",
"ratings": "1",
"price": 700,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
]
function filterBy(f) {
return data.filter(d => d.restaurant_dish_menus.some(({ menu_id }) => menu_id == f))
}
console.log(filterBy(4))
console.log(filterBy(3))

You can also use grep function
var menus= {
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
};
var found_names = $.grep(menus.restaurant_dish_menus, function(v) {
return v.menu_id ===4;
});
console.log(found_names);
http://jsfiddle.net/ejPV4/

Your question a bit unclear of final goal, but if you want to filter top level objects, i.e. if top level object has to be present if and only if it has dish with menu_id === filterBy, then:
let result = data.filter(row => {
return row.restaurant_dish_menus.some(({menu_id}) => menu_id === filterBy);
});
Above will only filter your rows if restaurant_dish_menus has items with menu_id === filterBy. But restaurant_dish_menus, of such objects remain unfiltered.
Result:
[{
"id": 68,
// skipped
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
// skipped
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
// skipped
}
]
}]
But if you want to filter top level and filter restaurant_dish_menus also, i.e. modify top level object, then:
let result = data.filter(row => {
return row.restaurant_dish_menus.some(({menu_id}) => menu_id === filterBy);
}).map(row => {
return {...row, restaurant_dish_menus: row.restaurant_dish_menus.filter(i => i.menu_id === filterBy)};
});
This will first filter the row objects which has menu_id === filterBy, and then also filter restaurant_dish_menus, to include only once menu_id === filterBy, effectively modifying the row object, i.e. map.
Result:
[{
"id": 68,
// skipped
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
// skipped
}
]
}]

Related

Get Particular value from Json Using Javascript or Jquery

I need to get only name value from below Json using Javscript or Jquery.
From below json I need to get key name values-Automation1, Automation2, Automation3
{
"status": [
[{
"id": 3,
"orgId": 1,
"name": "Automation1",
"email": "",
"Url": "",
"memberCount": 101,
"permission": 0
}, {
"id": 5,
"orgId": 1,
"name": "Automation2",
"email": "",
"Url": "",
"memberCount": 13,
"permission": 0
}, {
"id": 12,
"orgId": 1,
"name": "Automation3",
"email": "",
"Url": "/",
"memberCount": 25,
"permission": 0
}]
]
}

How to make advanced filter with jQuery

The Question;
I want to filter by properties.
I have json data coming from the api and I want to filter that data.(If there is a way to do with laravel I would like to try that too)
Json Data;
[
{
"id": 1,
"title": "Deneme Batarya",
"description": "<p>Deneme Batarya</p>",
"slug": "deneme-batarya",
"brand_id": 4,
"deleted_at": null,
"created_at": "2021-02-22 19:43:02",
"updated_at": "2021-02-22 19:43:02",
"categories": [
{
"id": 3,
"parent_id": null,
"title": "Giyilebilir Teknoloji",
"description": null,
"slug": "giyilebilir-teknoloji",
"media": "public/media/slider/ms-10.jpg",
"level": 0,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"pivot": {
"product_id": 1,
"category_id": 3
}
},
{
"id": 26,
"parent_id": 3,
"title": "Akıllı Bileklik",
"description": null,
"slug": "akilli-bileklik",
"media": "public/media/slider/ms-10.jpg",
"level": 2,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"pivot": {
"product_id": 1,
"category_id": 26
}
}
],
"images": [
{
"id": 3,
"product_id": 1,
"product_detail_id": 1,
"sku": "model-45b",
"image": "public/media/product/1-model-45b864.png",
"level": 1,
"deleted_at": null,
"created_at": "2021-02-24 19:49:16",
"updated_at": "2021-02-24 19:49:16"
},
{
"id": 4,
"product_id": 1,
"product_detail_id": null,
"sku": null,
"image": "public/media/product/1--501.jpeg",
"level": 1,
"deleted_at": null,
"created_at": "2021-02-24 19:53:27",
"updated_at": "2021-02-24 19:53:27"
}
],
"details": [
{
"id": 1,
"product_id": 1,
"qty": 5,
"status": "Available",
"price": "56.00",
"discount": 5,
"sku": "model-45b",
"start": "2021-02-22 00:00:00",
"end": "2021-02-23 00:00:00",
"deleted_at": null,
"created_at": "2021-02-22 19:43:27",
"updated_at": "2021-02-22 19:43:27"
},
{
"id": 2,
"product_id": 1,
"qty": 6,
"status": "Available",
"price": "90.00",
"discount": 4,
"sku": "model-45a",
"start": "2021-02-25 00:00:00",
"end": "2021-02-26 00:00:00",
"deleted_at": null,
"created_at": "2021-02-24 19:26:48",
"updated_at": "2021-02-24 19:26:48"
}
],
"properties": [
{
"id": 1,
"product_id": 1,
"product_detail_id": 1,
"property_id": 7,
"parent_id": 1,
"created_at": "2021-02-22 19:43:27",
"updated_at": "2021-02-22 19:43:27",
"property": {
"id": 7,
"parent_id": 1,
"title": "Green",
"slug": "green",
"value": "#008000",
"created_at": null,
"updated_at": null
},
"parent": {
"id": 1,
"parent_id": null,
"title": "Color",
"slug": "color",
"value": null,
"created_at": null,
"updated_at": null
}
},
{
"id": 2,
"product_id": 1,
"product_detail_id": 1,
"property_id": 20,
"parent_id": 3,
"created_at": "2021-02-22 19:43:27",
"updated_at": "2021-02-22 19:43:27",
"property": {
"id": 20,
"parent_id": 3,
"title": "1 TB",
"slug": "1-tb",
"value": "1 TB",
"created_at": null,
"updated_at": null
},
"parent": {
"id": 3,
"parent_id": null,
"title": "Store Capacity",
"slug": "store-capacity",
"value": null,
"created_at": null,
"updated_at": null
}
},
{
"id": 3,
"product_id": 1,
"product_detail_id": 2,
"property_id": 7,
"parent_id": 1,
"created_at": "2021-02-24 19:26:48",
"updated_at": "2021-02-24 19:26:48",
"property": {
"id": 7,
"parent_id": 1,
"title": "Green",
"slug": "green",
"value": "#008000",
"created_at": null,
"updated_at": null
},
"parent": {
"id": 1,
"parent_id": null,
"title": "Color",
"slug": "color",
"value": null,
"created_at": null,
"updated_at": null
}
},
{
"id": 4,
"product_id": 1,
"product_detail_id": 2,
"property_id": 12,
"parent_id": 2,
"created_at": "2021-02-24 19:26:48",
"updated_at": "2021-02-24 19:26:48",
"property": {
"id": 12,
"parent_id": 2,
"title": "L",
"slug": "l",
"value": "Large",
"created_at": null,
"updated_at": null
},
"parent": {
"id": 2,
"parent_id": null,
"title": "Size",
"slug": "size",
"value": null,
"created_at": null,
"updated_at": null
}
},
{
"id": 5,
"product_id": 1,
"product_detail_id": 2,
"property_id": 17,
"parent_id": 3,
"created_at": "2021-02-24 19:26:48",
"updated_at": "2021-02-24 19:26:48",
"property": {
"id": 17,
"parent_id": 3,
"title": "64 GB",
"slug": "64-gb",
"value": "64 GB",
"created_at": null,
"updated_at": null
},
"parent": {
"id": 3,
"parent_id": null,
"title": "Store Capacity",
"slug": "store-capacity",
"value": null,
"created_at": null,
"updated_at": null
}
}
]
}
]
I don't know the properties that user added because it is dynamic. So I'm reaching the properties like this.
function makeQueryString() {
function keyValues(idPref) {
var key = idPref,
values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() {
if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) {
return this.value;
}
}).get().join(',');
return key && values.length ? key + '=' + values : '';
}
return $('form#property-filter span[id]').map(function(){
let keyValue = keyValues(this.id);
if (keyValue != ''){
return keyValue;
}
}).get().join('&');
}
Properties Result;
id of properties with name
color=6,7&store-capacity=15,16,17&ram=21,22,23
EDIT
The main problem is make a filter using property result.
For example when user select Red And Blue color and click filter button it will return color=6,7 and I should filter my json data with this and bring only if include color 6 or 7. At the same time if user select red, 64GB, 128GB then it should return only if red color with 64 or 128.
I tried so far;
function filterProducts(prop) {
// prop = color=6,7&store-capacity=15,16,17&ram=21,22
prop = prop.split('&');
let x = [];
for (i=0; i<prop.length; i++){
x.push(prop[i].split('='));
}
let newProductsArr = [];
for (p=0; p<products.length; p++) {
for (k=0; k< products[p].properties.length; k++){
for (i=0; i<x.length; i++){
if(x[i][0] === products[p].properties[k].parent.slug){
let ids = x[i][1].split(',');
for (g=0; g<ids.length; i++){
if (products[p].properties[k].property_id === ids[g]){
newProductsArr.push(products[p])
}
}
}
}
}
}
}

Sorting an array of objects based on a string value's index in an array

I am trying to sort a dataset by the string rank based on their location in an array. I tried using indexOf with sort to limited success. I did find another post similar, although it is not relating to my question for any quick duplicate reporters.
Dataset:
[
{
"_id": {
"$oid": "5b535f6eddfad00564b103db"
},
"notes": [
"Very attractive"
],
"warns": [],
"username": "Saddy",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3c/3ce7fd0c1a5225790d67d90d4f1e60d2d29d2037_full.jpg",
"id": "76561198151478478",
"dateHired": {
"$date": "2018-07-21T16:29:34.563Z"
},
"profile": "https://steamcommunity.com/id/dpitt/",
"enactedBans": 0,
"currentTickets": 0,
"totalTickets": 0,
"rank": "Administrator",
"__v": 0
},
{
"_id": {
"$oid": "5b54d085ed4855275f4cea63"
},
"notes": [],
"warns": [],
"username": "meme master nick",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f6/f61f5d62b79b22c9183c049521a4c587ab9334cd_full.jpg",
"id": "76561198353773365",
"dateHired": {
"$date": "2018-07-22T18:44:21.814Z"
},
"profile": "https://steamcommunity.com/profiles/76561198353773365/",
"enactedBans": 0,
"currentTickets": 0,
"totalTickets": 0,
"rank": "Owner",
"__v": 0
},
{
"_id": {
"$oid": "5b567169e7179a32d9cc2abe"
},
"notes": [],
"warns": [],
"username": "DarkGamer2k16",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3d/3dd1f81fc4556ae984ebe2312e1b9fc4ba54b5ea_full.jpg",
"id": "76561194018842253",
"dateHired": {
"$date": "2018-07-21T16:29:34.563Z"
},
"profile": "https://steamcommunity.com/id/DarkGamer2k16/",
"enactedBans": 0,
"currentTickets": 0,
"totalTickets": 0,
"rank": "Moderator",
"__v": 0
}
]
Failed Attempts:
console.log(arr.sort(function(a){
return ["Owner", "Administrator", "Moderator"].indexOf(a.rank)
}))
arr.sort(function(a,b){
let sort = Object.assign({}, a, b);
return["Owner", "Administrator", "Moderator"].indexOf(sort.rank)
})
both of the above are just replacing all data with mine. Thank you for your assistance
Expected Output:
[
{
"_id": {
"$oid": "5b54d085ed4855275f4cea63"
},
"notes": [],
"warns": [],
"username": "meme master nick",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f6/f61f5d62b79b22c9183c049521a4c587ab9334cd_full.jpg",
"id": "76561198353773365",
"dateHired": {
"$date": "2018-07-22T18:44:21.814Z"
},
"profile": "https://steamcommunity.com/profiles/76561198353773365/",
"enactedBans": 0,
"currentTickets": 0,
"totalTickets": 0,
"rank": "Owner",
"__v": 0
},
{
"_id": {
"$oid": "5b535f6eddfad00564b103db"
},
"notes": [
"Very attractive"
],
"warns": [],
"username": "Saddy",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3c/3ce7fd0c1a5225790d67d90d4f1e60d2d29d2037_full.jpg",
"id": "76561198151478478",
"dateHired": {
"$date": "2018-07-21T16:29:34.563Z"
},
"profile": "https://steamcommunity.com/id/dpitt/",
"enactedBans": 0,
"currentTickets": 0,
"totalTickets": 0,
"rank": "Administrator",
"__v": 0
},
{
"_id": {
"$oid": "5b567169e7179a32d9cc2abe"
},
"notes": [],
"warns": [],
"username": "DarkGamer2k16",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3d/3dd1f81fc4556ae984ebe2312e1b9fc4ba54b5ea_full.jpg",
"id": "76561194018842253",
"dateHired": {
"$date": "2018-07-21T16:29:34.563Z"
},
"profile": "https://steamcommunity.com/id/DarkGamer2k16/",
"enactedBans": 0,
"currentTickets": 0,
"totalTickets": 0,
"rank": "Moderator",
"__v": 0
}
]
You need to use both a and b in the arguments provided to sort - compare by the difference of their indicies in the ["Owner", "Administrator", "Moderator"] array.
const input=[{"_id":{"$oid":"5b535f6eddfad00564b103db"},"notes":["Very attractive"],"warns":[],"username":"Saddy","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3c/3ce7fd0c1a5225790d67d90d4f1e60d2d29d2037_full.jpg","id":"76561198151478478","dateHired":{"$date":"2018-07-21T16:29:34.563Z"},"profile":"https://steamcommunity.com/id/dpitt/","enactedBans":0,"currentTickets":0,"totalTickets":0,"rank":"Administrator","__v":0},{"_id":{"$oid":"5b54d085ed4855275f4cea63"},"notes":[],"warns":[],"username":"meme master nick","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f6/f61f5d62b79b22c9183c049521a4c587ab9334cd_full.jpg","id":"76561198353773365","dateHired":{"$date":"2018-07-22T18:44:21.814Z"},"profile":"https://steamcommunity.com/profiles/76561198353773365/","enactedBans":0,"currentTickets":0,"totalTickets":0,"rank":"Owner","__v":0},{"_id":{"$oid":"5b567169e7179a32d9cc2abe"},"notes":[],"warns":[],"username":"DarkGamer2k16","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3d/3dd1f81fc4556ae984ebe2312e1b9fc4ba54b5ea_full.jpg","id":"76561194018842253","dateHired":{"$date":"2018-07-21T16:29:34.563Z"},"profile":"https://steamcommunity.com/id/DarkGamer2k16/","enactedBans":0,"currentTickets":0,"totalTickets":0,"rank":"Moderator","__v":0}]
const ranks = ["Owner", "Administrator", "Moderator"];
input.sort((a, b) => ranks.indexOf(a.rank) - ranks.indexOf(b.rank));
console.log(input);

Using angularjs forEach loops

I am getting this type of json in my $scope of angularjs:
$scope.someStuff = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [
{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
}
I want to use angularjs forEach loop and i want to get only category name,
My expected output:
[{"name":"software"}, {"name":"hardware"}, {"name":"waterwash"}]
You can use Array.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
$scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}})
var obj = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
};
console.log(obj.categoryservices.map((x) => {
return {
name: x.category.name
}
}))
You can use map method by passing a callback function as parameter.
const someStuff = { "id": 2, "service": "bike", "min": "22", "per": "100", "tax": "1", "categoryservices": [ { "id": 32, "category": { "id": 1, "name": "software" } }, { "id": 33, "category": { "id": 2, "name": "hardware" } }, { "id": 34, "category": { "id": 3, "name": "waterwash" } } ] }
let array = someStuff.categoryservices.map(function({category}){
return {'name' : category.name}
});
console.log(array);

How to find all unique paths in tree structure

root1
child1
child2
grandchild1
grandchild2
child3
root2
child1
child2
grandchild1
greatgrandchild1
I have an object array like tree structure like above, I want to get all unique paths in like this
Food->Dry Food Items->Local Dry Food Items
Food->Dry Food Items->Thai Dry Food Items
Food->Dry Food Items->Others
Food->Fruits
------
------
This is my object
[
{
"id": 1,
"name": "Food",
"parent_id": 0,
"children": [
{
"id": 5,
"name": "Dry Food Items",
"parent_id": 1,
"children": [
{
"id": 11,
"name": "Local Dry Food Items",
"parent_id": 5
},
{
"id": 12,
"name": "Thai Dry Food Items",
"parent_id": 5
},
{
"id": 60,
"name": "Others",
"parent_id": 5
}
]
},
{
"id": 6,
"name": "Fruits",
"parent_id": 1
},
{
"id": 7,
"name": "LG Branded",
"parent_id": 1
},
{
"id": 8,
"name": "Meat",
"parent_id": 1
},
{
"id": 9,
"name": "Sea food",
"parent_id": 1
},
{
"id": 10,
"name": "Vegetables",
"parent_id": 1,
"children": [
{
"id": 14,
"name": "Local Vegetables",
"parent_id": 10
},
{
"id": 15,
"name": "Thai Vegetables",
"parent_id": 10
}
]
},
{
"id": 38,
"name": "Frozen",
"parent_id": 1
},
{
"id": 39,
"name": "IP Kitchen",
"parent_id": 1,
"children": [
{
"id": 40,
"name": "IP Meat",
"parent_id": 39
},
{
"id": 41,
"name": "IP Starter",
"parent_id": 39
},
{
"id": 42,
"name": "IP Ingredients",
"parent_id": 39
},
{
"id": 43,
"name": "IP Sauce",
"parent_id": 39
},
{
"id": 44,
"name": "IP Seafood",
"parent_id": 39
},
{
"id": 45,
"name": "IP Starter",
"parent_id": 39
},
{
"id": 46,
"name": "IP Desert",
"parent_id": 39
}
]
}
]
},
{
"id": 2,
"name": "Beverage",
"parent_id": 0,
"children": [
{
"id": 16,
"name": "Bar",
"parent_id": 2
},
{
"id": 17,
"name": "Coffee & Tea",
"parent_id": 2
},
{
"id": 18,
"name": "In Can",
"parent_id": 2
},
{
"id": 19,
"name": "Water",
"parent_id": 2
},
{
"id": 47,
"name": "IP Bar",
"parent_id": 2
}
]
},
{
"id": 3,
"name": "Disposable",
"parent_id": 0,
"children": [
{
"id": 21,
"name": "Disposable",
"parent_id": 3
}
]
},
{
"id": 4,
"name": "SOE",
"parent_id": 0,
"children": [
{
"id": 20,
"name": "Cleaning Materials",
"parent_id": 4
},
{
"id": 22,
"name": "Chinaware",
"parent_id": 4
}
]
}
];
I get to all the nodes in the tree
function traverse(categories) {
categories.forEach(function (category) {
if (category.children && category.children.length) {
traverse(category.children);
}
else {
}
}, this);
}
You can use recursion and create a function using forEach loop.
var arr = [{"id":1,"name":"Food","parent_id":0,"children":[{"id":5,"name":"Dry Food Items","parent_id":1,"children":[{"id":11,"name":"Local Dry Food Items","parent_id":5},{"id":12,"name":"Thai Dry Food Items","parent_id":5},{"id":60,"name":"Others","parent_id":5}]},{"id":6,"name":"Fruits","parent_id":1},{"id":7,"name":"LG Branded","parent_id":1},{"id":8,"name":"Meat","parent_id":1},{"id":9,"name":"Sea food","parent_id":1},{"id":10,"name":"Vegetables","parent_id":1,"children":[{"id":14,"name":"Local Vegetables","parent_id":10},{"id":15,"name":"Thai Vegetables","parent_id":10}]},{"id":38,"name":"Frozen","parent_id":1},{"id":39,"name":"IP Kitchen","parent_id":1,"children":[{"id":40,"name":"IP Meat","parent_id":39},{"id":41,"name":"IP Starter","parent_id":39},{"id":42,"name":"IP Ingredients","parent_id":39},{"id":43,"name":"IP Sauce","parent_id":39},{"id":44,"name":"IP Seafood","parent_id":39},{"id":45,"name":"IP Starter","parent_id":39},{"id":46,"name":"IP Desert","parent_id":39}]}]},{"id":2,"name":"Beverage","parent_id":0,"children":[{"id":16,"name":"Bar","parent_id":2},{"id":17,"name":"Coffee & Tea","parent_id":2},{"id":18,"name":"In Can","parent_id":2},{"id":19,"name":"Water","parent_id":2},{"id":47,"name":"IP Bar","parent_id":2}]},{"id":3,"name":"Disposable","parent_id":0,"children":[{"id":21,"name":"Disposable","parent_id":3}]},{"id":4,"name":"SOE","parent_id":0,"children":[{"id":20,"name":"Cleaning Materials","parent_id":4},{"id":22,"name":"Chinaware","parent_id":4}]}]
function getNames(data) {
var result = [];
function loop(data, c) {
data.forEach(function (e) {
var name = !c.length ? e.name : c + '->' + e.name;
if (e.children) { loop(e.children, name); }
else {
result.push({ name: name });
}
});
}
loop(data, '');
return result;
}
console.log(getNames(arr))

Categories

Resources