how to show json array by hierarchical sub cats in react js - javascript

I receive through api one json with this structure.
And I want to display the objects as follows.
But I do not know in map array by react js how to get in objects and sub-objects.
json code:
[
{
"term_id": 15,
"name": "Uncategorized",
"children": [
]
},
{
"term_id": 21,
"name": "Clothing",
"children": [
{
"term_id": 24,
"name": "Accessories",
"children": [
{
"term_id": 24,
"name": "Accessories",
"children": [
]
},
{
"term_id": 23,
"name": "Hoodies",
"children": [
]
},
{
"term_id": 22,
"name": "Tshirts",
"children": [
]
}
]
},
{
"term_id": 23,
"name": "Hoodies",
"children": [
]
},
{
"term_id": 22,
"name": "Tshirts",
"children": [
]
}
]
},
{
"term_id": 26,
"name": "Decor",
"children": [
]
},
{
"term_id": 25,
"name": "Music",
"children": [
]
}
]
And I want to show it this way:
Uncategorized
Clothing
-Accessories
--Bike
--Engine
---Bench
--Airplane
Hoodies
Tshirts

I just answered a similar question to this one. So I'll just leave the link and copy paste the answer as well:
https://stackoverflow.com/a/66838788/15160090
Just let me know if you have any questions about this and I'll elaborate further on what you'd need to do.
For this kind of operation I suggest using Lodash. It's a very cool library with tons of useful methods to help you on your project.
https://lodash.com/docs/
Lodash has a groupBy method, easy to use, and I believe it does what you are looking for. So in your case, you would have something like this:
const categories = _.groupBy(data, "name");
You basically pass the array you want to group, along with the key name you want to group by.
Hope this was helpful.

You can use recursive function to solve your issue
function recursive(arrayJson, level=0)
{
let childrenComp = null
If(arrayJson.children)
childrenComp = recursive(arrayJson.children, level++)
return <>
<Text>{level > 0 && “-“.repeat(level)}arrayJson.name</Text>
{childrenComp}
</>
}
render(
const components = arrayJson && this.recursive(arrayJson)
return <View>{components}</View>
)

Related

Remove the first bracket from nested array

I have an array as follow:
let data =[
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}
],
[
{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}
]
]
I am trying to remove the first bracket to be like this:
let data =
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}
],
[
{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}
]
I have trying many solutions, the most common one i have tried is using this way:
let newData = data[0]
but the result always giving me the first nested array something like this:
[
{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10
}
]
I tried to convert it to string using JSON.stringify() then remove the bracket by doing
JSON.stringify(data).substring(1, JSON.stringify(data).length - 1);
But then when i parse it i get this error:
SyntaxError: JSON Parse error: Unable to parse JSON string
I am really stuck on what the best way to accomplish it.
thanks in advance.
You want the first element of each nested array, not the first element of the outer array. So use map().
let data = [
[{
"Id": "110d611c-54e4-4593-a835-def0f34ed882",
"duration": 30,
"name": "burger",
"price": 10,
}],
[{
"Id": "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
"duration": 10,
"name": "Cake",
"price": 5,
}]
];
let newData = data.map(el => el[0]);
console.log(newData);
Removing the external bracket will result in an invalid javascript object.
To obtain a single array with all the objects you can use flatMap
data.flatMap(x => x)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
The result that you want is not valid, instead you can get array of object using flat as:
data.flat()
let data = [
[
{
Id: "110d611c-54e4-4593-a835-def0f34ed882",
duration: 30,
name: "burger",
price: 10,
},
],
[
{
Id: "edc241e9-5caf-4f0b-b6ea-6cf5fc57d260",
duration: 10,
name: "Cake",
price: 5,
},
],
];
const result = data.flat();
console.log(result);

Insert key's value in the array of object having same key

Say I've an array of object:
const Info = [{
"id": "1aa2",
"details": [{
"name": "rusty",
"age": "12",
"favourite": [ObjectId("602b696cb783fc15845d015e"), ObjectId("602b696cb783fc15845d0112")]
}]
},
{
"id": "3aa2",
"details": [{
"name": "john",
"age": "122",
"favourite": [ObjectId("602b696cb783fc15845d0112s"), ObjectId("602b696cb783fc15845d01wqs")]
}]
}
]
I want to merge favourite in one array as:
["favourite": [
ObjectId("602b696cb783fc15845d015e"),
ObjectId("602b696cb783fc15845d0112"),
ObjectId("602b696cb783fc15845d0112s"),
ObjectId("602b696cb783fc15845d01wqs")
]
]
I tried using for loop but it's creating nasty nested for loop which is reducing performance a lot.
Basically, you need to iterate through Info collection, iterate through 'details' sub-collection, and copy all data into a new array. After, just create a new structure using favs variable content or paste this code as object value directly.
BTW your result array need's to contain an object at least, like that:
[ { favourite: [...] } ]
About nested structures, you should try https://lodash.com/docs/4.17.15#flatMapDeep (at least just check the code)
const Info = [{
"id": "1aa2",
"details": [{
"name": "rusty",
"age": "12",
"favourite": ['ObjectId("602b696cb783fc15845d015e")', 'ObjectId("602b696cb783fc15845d0112")']
}]
},
{
"id": "3aa2",
"details": [{
"name": "john",
"age": "122",
"favourite": ['ObjectId("602b696cb783fc15845d0112s")', 'ObjectId("602b696cb783fc15845d01wqs")']
}]
}
]
const favs = Info.reduce((acc, item) => {
item.details.forEach(detail => {
acc.push(...detail.favourite);
})
return acc;
}, []);
console.log(favs);

Remove special characters from a specific JSON object in JSON payload

I have a large JSON payload and I want to format, the specific object of the payload using JS.
I want flightdetails array object to edit and remove the special characters from it. How can I achieve this?
I have been working on this using XSLT for the past 2 days, and I went nowhere hence I decided to remove it using JS.
Example of the array(there can be more than 30 records inside the flightdetails)
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"\"return\",\"oneway\""
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"\"return\""
]
}
}
]
Expected Output
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"return","oneway"
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"return"
]
}
}
]
The flightdetails object inside the //destinations/flightdetails path

Underscore.js : findWhere with nested property value

How do I go about the filtering below:
[{
"id": 100,
"title": "Tlt1",
"tax": [{
"name": "Tax1",
"id": 15
}, {
"name": "Tax1",
"id": 17
}]
}, {
"id": 101,
"title": "Tlt2",
"tax": [{
"name": "Tax2",
"id": 16
}]
}, {
"id": 102,
"title": "Tlt3",
"tax": [{
"name": "Tax3",
"id": 17
}, {
"name": "Tax3",
"id": 18
}]
}]
to get only those where tax.id is 17, as per below:
[
{
"id": 100,
"title": "Tlt1",
"tax": [
{
"name": "Tax1",
"id": 15
},
{
"name": "Tax1",
"id": 17
}
]
},
{
"id": 102,
"title": "Tlt3",
"tax": [
{
"name": "Tax3",
"id": 17
},
{
"name": "Tax3",
"id": 18
}
]
}
]
Currently I use the method below, but maybe there is more clean way of going about this?
var arr = [];
_(data).each(function (v1, k1) {
_(v1.tax).each(function (v2, k2) {
if (v2.id == id) {
arr.push(v1);
}
});
});
Demo here: http://jsfiddle.net/7gcCz/2/
Any suggestion much appreciated.
You may use the combination of _.filter and _.where
_.filter(data, function(obj) {
return _.where(obj.tax, {id: ID_TO_FIND}).length > 0;
})
See demo: http://jsfiddle.net/hCVxp/
Update
Thanks to #GruffBunny. A more efficient way is to use _.some to avoid looping through all tax items:
var arr = _.filter(data, function(obj) {
return _.some(obj.tax, {id: ID_TO_FIND});
});
See demo: http://jsbin.com/putefarade/1/edit?html,js,console
Use _.filter to find candidate items and _.some to check for the existence of an item in a collection:
var filteredList = _.filter(list, function(item){
return _.some(item.tax, { id: 17 });
});
You can do this with _.where alone.
var filteredList = _.where(list, { tax:[{id:17}] });
Edit: This method works in older version of lodash, but wont work in current underscore or lodash.
Working example anyway:
https://jsfiddle.net/rhp4crma/

Searching and editing nested JSON elements

Basically I want to be able, in Javascript (JQuery optionally), to search into a JSON with nested elements for a particular element and edit it.
Ex. search for "components" with id 110 and change the name to "video card".
Notice the following JSON is just an example. I am wondering if javascript libraries or good tricks exist to do such a thing, I don't think traversing the whole json or writing my own methods is the best solution.
{
"computers": [
{
"id": 10,
"components": [
{
"id": 56,
"name": "processor"
},
{
"id": 24,
"name": "ram"
}
]
},
{
"id": 11,
"components": [
{
"id": 110,
"name": "graphic card"
},
{
"id": 322,
"name": "motherboard"
}
]
}
]
}
You could try linq.js.
You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = {
"computers": [
{
"id": 10,
"components": [
{ "id": 56, "name": "processor" },
{ "id": 24, "name": "ram" }
]
},
{
"id": 11,
"components": [
{ "id": 110, "name": "graphic card" },
{ "id": 322, "name": "motherboard" }
]
}
]
},
res = JSON.search( data, '//components[id=110]' );
res[0].name = 'video card';
Here is a working fiddle;
http://jsfiddle.net/g8fZw/
DefiantJS extends the global object JSON with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
http://www.defiantjs.com/#xpath_evaluator

Categories

Resources