JS Recursive Nested JSON Array Children Join Key - javascript

[
{
"PRODUCT_CATEGORY_ID": "1",
"NAME": "OTOMOBİL PARÇALARI",
"DESCRIPTION": "Araba Parçaları",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "",
"children": [
{
"PRODUCT_CATEGORY_ID": "3",
"NAME": "HONDA PARÇALARI",
"DESCRIPTION": "Honda Parçaları",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "1"
},
{
"PRODUCT_CATEGORY_ID": "4",
"NAME": "RENAULT PARÇALARI",
"DESCRIPTION": "Renault Parçaları",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "1",
"children": [
{
"PRODUCT_CATEGORY_ID": "5",
"NAME": "MINIMAL RENAULT PARÇALARI",
"DESCRIPTION": "",
"ACTIVE": "True",
"PARENT_PRODUCT_CATEGORY_ID": "4"
}
]
}
]
}
]
I have a json with nested children and I want the paths of this object's children. nested children can be even more.I want as output is a string array.
[
"OTOMOBİL PARÇALARI"
"OTOMOBİL PARÇALARI > HONDA PARÇALARI"
"OTOMOBİL PARÇALARI > RENAULT PARÇALARI"
"OTOMOBİL PARÇALARI > RENAULT PARÇALARI > MINIMAL RENAULT PARÇALARI"
]
I tried
function findAllChildren (id, results, depth) {
for (d in data) {
if (data[d].parent == id) {
data[d].depth = depth
results.push(data[d])
findAllChildren(data[d].id, results, depth + 1)
}
}
}
var results = []
findAllChildren(1, results, 0)
return results.map(function (element) { return Array(element.depth + 1).join(' -> ') + element.name})
Thank you for your help in advance, I searched and couldn't find it, you can share it with me in the link.

You can use a a recursive approach, say, creating a function getPaths that will get a list of paths using a property key as an input.
In this case we'll use 'NAME', and build up an array of the relevant paths.
let input = [ { "PRODUCT_CATEGORY_ID": "1", "NAME": "OTOMOBİL PARÇALARI", "DESCRIPTION": "Araba Parçaları", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "", "children": [ { "PRODUCT_CATEGORY_ID": "3", "NAME": "HONDA PARÇALARI", "DESCRIPTION": "Honda Parçaları", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "1" }, { "PRODUCT_CATEGORY_ID": "4", "NAME": "RENAULT PARÇALARI", "DESCRIPTION": "Renault Parçaları", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "1", "children": [ { "PRODUCT_CATEGORY_ID": "5", "NAME": "MINIMAL RENAULT PARÇALARI", "DESCRIPTION": "", "ACTIVE": "True", "PARENT_PRODUCT_CATEGORY_ID": "4" } ] } ] } ]
function getPaths(obj, property, path = '') {
const paths = [];
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
paths.push(...getPaths(obj[k], property, path));
} else if (k === property) {
path += (path ? ' > ' : '') + obj[k];
paths.push(path)
}
}
return paths;
}
console.log('Paths:', getPaths(input, 'NAME'))

Related

Find element in array of x depth Javascript

Is it possible to use the find() method within an array of depth x?
For example, suppose I have the following array of objects, call it test:
[
{
"id": "1",
"title": "First",
},
{
"id": "2",
"title": "Second",
"movies": [
{
"id": "3",
"title": "Happy Gilmore",
"Actors": [
{
"id": "4",
"title": "John Doe",
},
{
"id": "5",
"title": "Jane Doe",
},
],
"Producers": [
{
"id": "6",
"title": "Max Smith",
},
{
"id": "7",
"title": "Richard Rocky",
},
],
},
{
"id": "10",
"title": "Billy Madison",
"Actors": [
{
"id": "40",
"title": "John Smith",
},
{
"id": "50",
"title": "Alex Doe",
},
],
"Producers": [
{
"id": "60",
"title": "Bob Smith",
},
{
"id": "70",
"title": "Polly Rocky",
},
],
}
]
}
]
Suppose I am looking for the "2" id. I can use the find() method to search the first level of the array and return the desired object by doing test.find(element => element.id === "2").
However, suppose I am now looking for the occurrence where the id is 4. As you can see from the above JSON, that element is within a sub array within test. Is there a way therefore where I can still search through test to find the element where id=4?
find cannot do this, but you can use it in a recursive approach:
function findDeep(arr, predicate) {
let res = arr.find(predicate);
if (res !== undefined) return res;
for (let obj of arr) {
for (let value of Object.values(Object(obj)).filter(Array.isArray)) {
res = findDeep(value, predicate);
if (res !== undefined) return res;
}
}
}
let test = [{"id": "1","title": "First",},{"id": "2","title": "Second","movies": [{"id": "3","title": "Happy Gilmore","Actors": [{"id": "4","title": "John Doe",},{"id": "5","title": "Jane Doe",},],"Producers": [{"id": "6","title": "Max Smith",},{"id": "7","title": "Richard Rocky",},],},{"id": "10","title": "Billy Madison","Actors": [{"id": "40","title": "John Smith",},{"id": "50","title": "Alex Doe",},],"Producers": [{"id": "60","title": "Bob Smith",},{"id": "70","title": "Polly Rocky",},],}]}];
let res = findDeep(test, obj => obj.id == "4");
console.log(res);

How can I concatenate this type of JSON in javascript?

How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.

How to get the corresponding value from two objects

I have first data object which has a list of cafe, and second data object which has a list of cafe types.
I need find, get and display the corresponding type value from first data object and ID value from second data object.
For example: in list of cafe, I have Pinta with "type" : "3", it means that 3 is Bar from second object.
First object:
{
"list": {
"item": [
{
"ID": "31",
"name": "Staut",
"type": "1",
},
{
"ID": "34",
"name": "Pinta",
"type": "3",
}
]
}
}
And second object:
{
"list": {
"item": [
{
"ID": "1",
"name": "Restaurant",
},
{
"ID": "2",
"name": "Cafe",
},
{
"ID": "3",
"name": "Bar",
}
]
}
}
I can do it with Lodash. It is right, but I can't display it and it uses high memory.
getValues: function() {
_.forEach(CafeJSON.list.item, function(cafeValue) {
_.forEach(TypeJSON.list.item, function(typeValue){
if (cafeValue.type == typeValue.ID) {
console.log("Cafe name is: ", cafeValue.name, "and type is: ", typeValue.name)
}
})
})
}
Result:
I'd simplify the types object down to a object having key value pairs in the form of '3': 'Bar', then loop the items once, overriding the type property's value.
let list = {
"list": {
"item": [{
"ID": "31",
"name": "Staut",
"type": "1",
},
{
"ID": "34",
"name": "Pinta",
"type": "3",
}
]
}
}
let types = {
"list": {
"item": [{
"ID": "1",
"name": "Restaurant",
},
{
"ID": "2",
"name": "Cafe",
},
{
"ID": "3",
"name": "Bar",
}
]
}
}
let typesSimplified = types.list.item.reduce((a, b) => {
a[b.ID] = b.name;
return a;
}, {});
list.list.item.forEach(e => {
e.type = typesSimplified[e.type];
});
console.log(list);

How to Sort the JSON array in the controller of AngularJS?

Kindly help me in sorting the below JSON list in the controller and display in the view.
Actually orderBy filter sorting one level, But I need it sort even for childs recursively.
Input:
R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1
Output:
R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4
Please find the sample in Plunker.
http://plnkr.co/edit/JslHwJ1CBREKf6FgYHaZ?p=preview
var sortNames = function(arr){
arr = arr.sort(function(a,b){
return a.name > b.name;
})
for (var i = 0; i < arr.length; i++){
if (arr[i].childs){
sortNames(arr[i].childs)
}
}
return arr;
}
var names = [
{
"name": "Root1",
"Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
"status": "",
"dispName": "",
"imageURL": "",
"childCount": "",
"childs": [
{
"name": "Sub1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
"childs": [
{
"name": "Template1",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
"status": "",
"dispName": "",
"imageURL": ""
},
{
"name": "Template2",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
"status": "",
"dispName": "",
"imageURL": ""
}
]
},
{
"name": "Template3",
"Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"
}
]
},
{
"name": "Root2",
"Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
"childs": [
{
"name": "Sub2",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
"childs": [
{
"name": "Template4",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
},
{
"name": "Template5",
"Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
}
]
}
]
}
];
sortNames(names);

How to add some code inside the JavaScript array?

Enviroment: Visual Studio 2012, MVC4, Razor, Internet Application.
I have a JavaScript array..
var over100 = "#Model.Over100";
var filterarray = [
{
"name": "Condition",
"value": "New",
"paramName": "",
"paramValue": ""
},
{
"name": "FreeShippingOnly",
"value": "false",
"paramName": "Currency",
"paramValue": "USD"
},
];
In case of... if(over100 != null)
I want...
var filterarray = [
{
"name": "Condition",
"value": "New",
"paramName": "",
"paramValue": ""
},
{
"name": "FreeShippingOnly",
"value": "false",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "Over100",
"value": "true",
"paramName": "",
"paramValue": ""
},
];
I would like to know all the possible ways, how to do that.
Thank You!
You can use push():
if(over100 != ''){
var addfilter = {"name": "Over100",
"value": "true",
"paramName": "",
"paramValue": ""}
filterarray.push(addfilter)
}
if(over100 != null) {
filterarray.push({"name": "Over100", "value": "true", "paramName": "", "paramValue": ""})
}

Categories