Write a function that takes Season number and episode number as input
and gives all the information about that particular episode as output
After taking inputs from the user as season number and episode number, it doesn't give output as the information about that particular episode
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
let season = prompt('Enter Season number');
let number = prompt('Enter Episode number');
let AllInfo = (season,number) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].season === season) {
if(BigBang._embedded.episodes[current].number === number) {
let Detail = BigBang._embedded.episodes[current];
alert(Detail);
}
}
}
AllInfo(season,number);
}
Try using .find instead, it'll make the code a lot cleaner:
let BigBang = {
"_embedded": {
"episodes": [{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
]
}
}
//const inputSeason = prompt('Enter Season number');
const inputSeason = 1;
//const inputNumber = prompt('Enter Episode number');
const inputNumber = 2;
const foundEpisode = BigBang._embedded.episodes.find(({ season, number}) => {
return season === inputSeason && number === inputNumber;
});
if (foundEpisode) console.log(foundEpisode);
else console.log('No matching season/number found!');
You could do that easier with the find() method on your array.
let episode = BigBang._embedded.episodes.find((e) => {
return e.season === season && e.number === number;
});
if (episode) {
alert(episode.name);
}
I have debugged your code and saw that you call AllInfo function within AllInfo .So there is recursive call happen in your code. So remove calling of AllInfo from AllInfo function, your issue will be fixed. Try the following code.
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}]}};
let season = 1;
let number = 2;
let AllInfo = (season,number) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].season === season) {
if(BigBang._embedded.episodes[current].number === number) {
let Detail = BigBang._embedded.episodes[current];
alert(JSON.stringify(Detail,null,4));
}
}
}
}
AllInfo(season,number);
Related
I have an JSON file with data inside of an user
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden#xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
},
{
"_id": "62bd5fbaf8f417d849c135db",
"index": 2,
"email": "pattyowen#xerex.com",
"nameList": [
{
"id": 0,
"name": "Earline Goff"
},
{
"id": 1,
"name": "Glenna Lawrence"
},
{
"id": 7,
"name": "Bettye Sawyer"
}
]
I had to sort every user by : if user has more than two names
if user ids are consecutive
and if user ids are numbers
I managed to sort user by more than two names and if ids are consecutive
userData.filter(({nameList}) =>
nameList.length > 2 &&
!nameList.some(({id}, index, array) => index && array[index - 1].id !== id - 1)
);
In the case that an object has an id as number I should not return the objects. How can I implement that in my code?
The output is expected to be all the arrays that meet the filter, and some() criteria. Which is if objects has more than 2 names, its ids are consecutive and the ids should be a number.
If you want to check if the id is of type number:
(typeof id == "number")
To check if can be cast to a number
(id == parseInt(id, 10))
The complete code then (you were close):
var userData = get_data();
userData = userData.filter(function(item) {
return item.nameList.length > 2 &&
item.nameList.every(function(item, index, arr) {
return parseInt(item.id) == item.id && (index == 0 || item.id - arr[index - 1].id == 1)
})
})
console.log(userData);
function get_data() {
return [{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden#xerex.com",
"nameList": [{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
},
{
"_id": "62bd5fbaf8f417d849c135db",
"index": 2,
"email": "pattyowen#xerex.com",
"nameList": [{
"id": 0,
"name": "Earline Goff"
},
{
"id": 1,
"name": "Glenna Lawrence"
},
{
"id": 7,
"name": "Bettye Sawyer"
}
]
}
];
}
.as-console-wrapper {
max-height: 100% !important
}
I have an array of objects called orders:
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}
]
}
];
I need to get the quantity when both the order_type (Wholesale) and items.detail.ID (13363) match.
I have so far tried the following:
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if(item.detail.ID == 13363) {
return item.quantity;
}
}, 0);
Where result correctly returns 4
My issue, and I'm sure I am missing something very simple is that when I have multiple items in my orders array, it fails.
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
},
{
"id": 56,
"department": "Womens",
"type": "Skirt",
"quantity": 12,
"detail": {
"ID": 76884,
"On Sale": 0,
}
},
{
"id": 89,
"department": "Mens",
"type": "Shirts",
"quantity": 20,
"detail": {
"ID": 98223,
"On Sale": 1,
}
}
]
}
];
The same
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if(item.detail.ID == 13363) {
return item.quantity;
}
}, 0);
returns undefined
Thank you
The find helper just returns the first match, so you need to use another helper like filter, like this:
const ID = 13363;
const result = orders
.filter((order) => order.order_type === 'Wholesale')
.reduce((acc, curr) => {
const items = curr.items.filter((item) => item.detail.ID === ID);
console.log(items);
// You can sum the matching items and then push them into the acc array
const quantity = items.reduce((sum, item) => (sum += item.quantity), 0);
acc.push(quantity);
return acc;
}, []);
This will return an array of matching quantities.
Not sure about the use case but here you go
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if (item.detail.ID == 13363) {
total += item.quantity;
}
return total
}, 0);
You can even create a function to make the search dynamic.
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
},
{
"id": 56,
"department": "Womens",
"type": "Skirt",
"quantity": 12,
"detail": {
"ID": 76884,
"On Sale": 0,
}
},
{
"id": 89,
"department": "Mens",
"type": "Shirts",
"quantity": 20,
"detail": {
"ID": 98223,
"On Sale": 1,
}
}
]
}
];
findMyItem=( ID )=>{
var result = null ;
const result2 = orders.find(item => item.order_type == "Wholesale").items
.map(( item) => {
if(item.detail.ID == ID ) {
result = item.quantity;
}
}, 0);
return result ;
}
console.log( "result" ,findMyItem( 13363 ) )
console.log( "result" ,findMyItem( 98223) )
console.log( "result" ,findMyItem( 76884) )
You could use Array.find() on the orders array to find the correct order, searching for the first order that matches both the order_type and has an item matching the desired itemId (using Array.some()).
If this order exists, we can then find the corresponding item quantity using .find() again,
const orders = [ { "order_id": 47445, "order_type": "Wholesale", "items": [ { "id": 9, "department": "Womens", "type": "Dress", "quantity": 4, "detail": { "ID": 13363, "On Sale": 1, } }, { "id": 56, "department": "Womens", "type": "Skirt", "quantity": 12, "detail": { "ID": 76884, "On Sale": 0, } }, { "id": 89, "department": "Mens", "type": "Shirts", "quantity": 20, "detail": { "ID": 98223, "On Sale": 1, } } ] } ]
function findItemQuantity(orders, orderType, itemId) {
// Find the first order with the right order_type and containing the right item id
const order = orders.find(order => order.order_type = orderType && order.items.some(item => item.detail.ID === itemId));
if (!order) {
return null;
}
const item = order.items.find(item => item.detail.ID === itemId);
if (!item) {
return null;
}
return item.quantity;
}
console.log("Quantity found:", findItemQuantity(orders, 'Wholesale', 13363))
console.log("Quantity found:", findItemQuantity(orders, 'Wholesale', 76884))
const result = orders
.filter(order => order.order_type == "Wholesale")
.map(order => order.items.find(item => item.detail.ID == 13363))
.filter(item => item)
.reduce((total, { quantity }) => quantity + total, 0);
const orders = [{
"order_id": 47445,
"order_type": "Wholesale",
"items": [{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}]
},
{
"order_id": 47445,
"order_type": "Whole",
"items": [{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}]
}
]
const result = orders.reduce(v => {
return v.items.map(a => {
if (v.order_type == 'Wholesale' && a.detail.ID == 13363) {
return v
}
})
})
console.log(result)
const orders = [{
"order_id": 47445,
"order_type": "Wholesale",
"items": [{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}]
}];
var result = null;
const result2 = orders.find(item => item.order_type == "Wholesale").items
.map((item) => {
if (item.detail.ID == 98223) {
result = item.quantity;
}
}, 0);
console.log("result", result)
This is essentially what the payload looks like from my API. I'd like to reshape the data so I can dynamically display the data on the frontend without hard coding things like column names. For what it's worth I'm using DRF, axios, and react-redux. That said I think I just need to learn more vanilla js :/
*purposely have a different number of keys in 1 entry vs another.
data =[
{
"id": 1,
"j_column": {
"name": "James",
"outside_id": 1,
"alt_name": "Jim",
"full_name": "James the third"
}
},
{
"id": 3,
"j_column": {
"name": "Dennis",
"outside_id": 57,
"alt_name": "Denny",
"full_name": "Dennis the third",
"nickname": "Denny the super star"
}
}]
newData =[
{
"id": 1,
"name": "James",
"outside_id": 1,
"alt_name": "Jim",
"full_name": "James the third"
},
{
"id": 3,
"name": "Dennis",
"outside_id": 57,
"alt_name": "Denny",
"full_name": "Dennis the third",
"nickname": "Denny the super star"
}]
This is one way to do it:
const data =[
{
"id": 1,
"j_column": {
"name": "James",
"outside_id": 1,
"alt_name": "Jim",
"full_name": "James the third"
}
},
{
"id": 3,
"j_column": {
"name": "Dennis",
"outside_id": 57,
"alt_name": "Denny",
"full_name": "Dennis the third",
"nickname": "Denny the super star"
}
}];
const newData = data.map((el) => {
const obj = {...el.j_column};
obj.id = el.id;
return obj;
});
console.log(newData);
var new_data = [];
data.map(item => {
var obj = {};
Object.keys(item).map(itemKey => {
if (typeof item[itemKey] !== 'object') {
obj[itemKey] = item[itemKey]
}else
Object.keys(item[itemKey]).map(subItemKey => {
obj[subItemKey] = item[itemKey][subItemKey]
})
})
new_data.push(obj);
})
console.log(new_data);
I want to access: order_items > items > order_item_name
{
"order_id": 14858,
"parent_id": 0,
"date_created": "2020-05-17 07:31:42",
"date_created_gmt": "2020-05-17 07:31:42",
"status": "wc-completed",
"customer_id": 9,
"customer": {
"customer_id": 9,
"user_id": 3,
"username": "husam",
"first_name": "Hosam",
"last_name": "amazon",
"email": "ecommerce#amazonfoods.ae",
},
"order_items": [
{
"order_item_id": 152,
"order_id": 14858,
"product_id": 9095,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 152,
"order_item_name": "Amazon Cheddar Cheese, 50g",
"order_item_type": "line_item",
"order_id": 14858
}
},
{
"order_item_id": 153,
"order_id": 14858,
"product_id": 9063,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 153,
"order_item_name": "Amazon 1121 Golden Sella Rice, 5kg",
"order_item_type": "line_item",
"order_id": 14858
}
},
]
},
Since it is in the loop and can be seen here:
const ordersTest = [];
for (let i = 0; i < props.allOrdersState.length &&
props.allOrdersState.length; i++) {
ordersTest.push({
state:props.allOrdersState.length ? props.allOrdersState[i]['customer']['state'] :'',
first_name:props.allOrdersState.length ? props.allOrdersState[i]['customer']['first_name'] :'',
orderItems: [{
itemName:props.allOrdersState.length ? props.allOrdersState[i]['order_items'][i]['item']['order_item_name'] :'',
}],
});
}
I want to access the order_item_name but it gives an error of undefined. however, the first name and other details can be accessed.
It looks like each order has multiple orderItems, so I assume you are trying to map them? The length conditionals weren't needed since the for loop would not have run if length equaled 0. Also, there is no "state" property so I changed it to "status".
for (let i = 0; i < props.allOrdersState.length; i++) {
ordersTest.push({
status: props.allOrdersState[i]['status'],
first_name: props.allOrdersState[i]['customer']['first_name'],
orderItems: props.allOrdersState[i].order_items.map((oi) => ({
itemName: oi['item']['order_item_name']
}))
})
}
const props = {
allOrdersState: [
{
"order_id": 14858,
"parent_id": 0,
"date_created": "2020-05-17 07:31:42",
"date_created_gmt": "2020-05-17 07:31:42",
"status": "wc-completed",
"customer_id": 9,
"customer": {
"customer_id": 9,
"user_id": 3,
"username": "husam",
"first_name": "Hosam",
"last_name": "amazon",
"email": "ecommerce#amazonfoods.ae",
},
"order_items": [
{
"order_item_id": 152,
"order_id": 14858,
"product_id": 9095,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 152,
"order_item_name": "Amazon Cheddar Cheese, 50g",
"order_item_type": "line_item",
"order_id": 14858
}
},
{
"order_item_id": 153,
"order_id": 14858,
"product_id": 9063,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 153,
"order_item_name": "Amazon 1121 Golden Sella Rice, 5kg",
"order_item_type": "line_item",
"order_id": 14858
}
},
]
}
]
}
const ordersTest = [];
for (let i = 0; i < props.allOrdersState.length; i++) {
ordersTest.push({
status: props.allOrdersState[i]['status'],
first_name: props.allOrdersState[i]['customer']['first_name'],
orderItems: props.allOrdersState[i].order_items.map((oi) => ({
itemName: oi['item']['order_item_name']
}))
})
}
console.log(ordersTest)
You can use the recursive method to find the fields you want.
let answer = [];
function indexOf(obj, to) {
if (obj.hasOwnProperty(to)) {
answer.push(obj[to]);
} else if(Object.prototype.toString.call(obj) === '[object Object]') {
Object.values(obj).filter(item => typeof (item) === 'object').map(item => {
let newObj = item;
indexOf(newObj, to);
})
} else if(Object.prototype.toString.call(obj) === '[object Array]') {
obj.map(item=>{
let newObj = item;
indexOf(newObj, to);
})
}
return answer;
}
My method is a little lax, but it's OK to meet your requirements.
const obj = {
"order_id": 14858,
"parent_id": 0,
"date_created": "2020-05-17 07:31:42",
"date_created_gmt": "2020-05-17 07:31:42",
"status": "wc-completed",
"customer_id": 9,
"customer": {
"customer_id": 9,
"user_id": 3,
"username": "husam",
"first_name": "Hosam",
"last_name": "amazon",
"email": "ecommerce#amazonfoods.ae",
},
"order_items": [
{
"order_item_id": 152,
"order_id": 14858,
"product_id": 9095,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 152,
"order_item_name": "Amazon Cheddar Cheese, 50g",
"order_item_type": "line_item",
"order_id": 14858
}
},
{
"order_item_id": 153,
"order_id": 14858,
"product_id": 9063,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 153,
"order_item_name": "Amazon 1121 Golden Sella Rice, 5kg",
"order_item_type": "line_item",
"order_id": 14858
}
},
]
};
let answer = [];
function indexOf(obj, to) {
if (obj.hasOwnProperty(to)) {
answer.push(obj[to]);
} else if(Object.prototype.toString.call(obj) === '[object Object]') {
Object.values(obj).filter(item => typeof (item) === 'object').map(item => {
let newObj = item;
indexOf(newObj, to);
})
} else if(Object.prototype.toString.call(obj) === '[object Array]') {
obj.map(item=>{
let newObj = item;
indexOf(newObj, to);
})
}
return answer;
}
console.log(indexOf(obj, 'order_item_name'));
I just solved the issue. I pushed the orderItems along with firstName and other details to the empty array(ordersTest = [];) and all the items moved to the array and then I accessed each item details and order details from the array.
for (let i = 0; i < props.allOrdersState.length &&
props.allOrdersState.length; i++) {
ordersTest.push({
state:props.allOrdersState.length ? props.allOrdersState[i]['customer']['state'] :'',
first_name:props.allOrdersState.length ? props.allOrdersState[i]['customer']['first_name'] :'',
orderItems: [{
itemName:props.allOrdersState.length ? props.allOrdersState[i]['order_items']:'',
}],
});
}````
Then I accessed each element like:
{row.itemName.map((historyRow) => (
<div style={{border:'1px solid #041e41',padding:'10px'}}>
<Typography>{historyRow.item.order_item_name}</Typography>
<Typography gutterBottom component="div">
<strong> Shipment Amount:</strong> {historyRow.shipping_amount}
</Typography>
<Typography>
<strong> product Quantity:</strong> {historyRow.product_qty}
</Typography>
<Typography>
<strong>Tax Amount:</strong> {historyRow.tax_amount}
</Typography>
</div>
))}
I have mapped over row because I am mapping rows of the table and inside each row i have take collapsed of material UI, so each row contains single record:
<TableBody>
{ordersTest.map((row) => (
<Row key={row.order_id} row={row} />
))}
</TableBody>
And in each single record I am fetching detials and there is again loop over items.
I'm trying to implement a search box in which if i start searching for a value it will look for the target in an nested array of objects which is like this:--
[
{
"groupId": 1,
"groupName": "Americas",
"groupItems": [
{
"id": 5,
"name": "Brazil",
"parentID": 1,
"parentName": "Americas"
},
{
"id": 6,
"name": "Canada",
"parentID": 1,
"parentName": "Americas"
}
],
"isExpanded": false,
"toggleAllSelection": false
},
{
"groupId": 2,
"groupName": "APAC",
"groupItems": [
{
"id": 7,
"name": "Australia",
"parentID": 2,
"parentName": "APAC"
},
{
"id": 8,
"name": "China",
"parentID": 2,
"parentName": "APAC"
}
],
"isExpanded": false,
"toggleAllSelection": false
},
{
"groupId": 3,
"groupName": "Europe",
"groupItems": [
{
"id": 9,
"name": "Belgium",
"parentID": 3,
"parentName": "Europe"
},
{
"id": 7,
"name": "Austria",
"parentID": 2,
"parentName": "APAC"
},
{
"id": 10,
"name": "Bulgaria",
"parentID": 3,
"parentName": "Europe"
}
],
"isExpanded": false,
"toggleAllSelection": false
}
]
Now i want to search for name property in each groupItems array of objects in group array. and when there is a match my function should return data in same format and as it will be autocomplete so instead of exact match it should be partial match. So if search aus in input box it should return
[{
"groupId": 2,
"groupName": "APAC",
"groupItems": [
{
"id": 7,
"name": "Australia",
"parentID": 2,
"parentName": "APAC"
}],
"isExpanded": false,
"toggleAllSelection": false,
},
{
"groupId": 3,
"groupName": "Europe",
"groupItems": [
{
"id": 7,
"name": "Austria",
"parentID": 2,
"parentName": "APAC"
}
],
"isExpanded": false,
"toggleAllSelection": false
}
]
const findByName = (data, name) => {
const result = data.reduce((m, { groupItems, ...rest }) => {
let mapGrpItems = (groupItems || []).filter((item) =>
item.name.includes(name)
);
if (mapGrpItems.length) {
m.push({ ...rest, groupItems: mapGrpItems });
}
return m;
}, []);
return result;
};
const findByName = (data, name) => {
const result = data.reduce((m, { groupItems, ...rest }) => {
let mapGrpItems = (groupItems || []).filter((item) =>
item.name.includes(name)
);
if (mapGrpItems.length) {
m.push({ ...rest, groupItems: mapGrpItems });
}
return m;
}, []);
return result;
};
const data = [{"groupId":1,"groupName":"Americas","groupItems":[{"id":5,"name":"Brazil","parentID":1,"parentName":"Americas"},{"id":6,"name":"Canada","parentID":1,"parentName":"Americas"}],"isExpanded":false,"toggleAllSelection":false},{"groupId":2,"groupName":"APAC","groupItems":[{"id":7,"name":"Australia","parentID":2,"parentName":"APAC"},{"id":8,"name":"China","parentID":2,"parentName":"APAC"}],"isExpanded":false,"toggleAllSelection":false},{"groupId":3,"groupName":"Europe","groupItems":[{"id":9,"name":"Belgium","parentID":3,"parentName":"Europe"},{"id":7,"name":"Austria","parentID":2,"parentName":"APAC"},{"id":10,"name":"Bulgaria","parentID":3,"parentName":"Europe"}],"isExpanded":false,"toggleAllSelection":false}]
console.log(JSON.stringify(findByName(data, "Aus"), null, 2));
I would definitely attempt to reason through what you're trying to do before just implementing this. Being able to reason through solutions like this is 99% of the job when it comes to programming.
function filterGroups(filter) {
const result = [];
myObj.forEach(group => {
const filteredGroups = group.groupItems.filter(groupItem => {
return groupItem.name.toLowerCase().includes(filter);
});
if (filteredGroups.length > 1) {
result.push({
...group,
groupItems: filteredGroups
});
}
});
return result;
}
You can use Arrays.filter for the group items in each outer object in your JSON array to filter out the items which match your search query. You can write something like this:
let autocomplete = (key) => {
// arr = Your Data
let result = []
arr.forEach(grp=> {
let out = grp
let res = grp.groupItems.filter(item => item.name.toLowerCase().includes(key.toLowerCase()))
if(res.length!=0)
{
out.groupItems = res
result.push(out)}
})
return result