So, I'm relatively new to javascript, and I'm working with a client-side javascript function that inserts JSON results pushed to it from the server.
I would like to stop certain results, independently of that javascript that populating the results.
Usually, if the js was my own, I'd make a guess that I'd use the "splice" function to remove the JSON array entry(ies) that I don't wish to be there, does that sound about right? (I'd got to there through plenty of searching on StartPage and here)
However, I need whatever function I (let's be honest, "you") come up with to trump the embedded results.
Essentially this is normal behaviour:
Webpage > JavaScript Parses JSON for Initial Results
then
Webpage > Scroll > JavaScript Parses JSON for More Results
I'd like to insert something that will stop any JSON items that I don't like. I don't know how to represent that, I'd assume:
Worker in Extension/Add-On > Webpage > etc
I doubt this can be done with CSS ... but that'd be awesome, as I'd just put it in my personal.
If it was splice, I'd have a vague idea (but really I'm flying blind) of how to do it on a base level with splice, but I'm already struggling, and that would deepen for the insanely deeply embedded objects I'm trying to exclude.
So. There is lot of json data in the section I'm looking at.
I'm purely concentrated on the removing of the array here, but by end goal is two parts:
In the ' contents ' array in levelOneB's ' daContentShaper ' I would
like to remove any item from the array where in the sub-object '
content ' there is an element called ' contentTypeA '. There's another
object with the label ' ahThisIsTheBContent ', which I'd also like gone,
and that's dotted through the JSON. All other items (TypeB, TypeC, or
other) must stay.
Additionally, within said ' content ' object I would like to change any ' visible ' values that are " false " to " true ".
It's definitely possible, it's just working out how to ensure that the rest of the code (which may have similar - not the same - parts elsewhere) isn't affected by my splice of this array.
{
"levelOneA": {
"levelOneAArr": [ { "name": "me", "age": 1 }, { "name": "you", "age": 2 }, { "name": "them", "age": 3 } ],
"levelOneAText": "blah"
},
"levelOneB": {
"levelOneBDeepBro": {
"levelOneBDeepBroTabs": [
{
"levelOneBDeepBroTabsShaper": {
"isBlessed": true,
"daContent": {
"daContentShaper": {
"contents": [
{
"contentItem": {
"content": {
"contentTypeA": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "cripes"
},
{
"bitBText1": "crikey"
},
{
"bitBText1": "crimeny"
}
],
"visible": true
}
},
"extraNonsense": "bingoBlah"
}
},
{
"contentItem": {
"content": {
"ahThisIsTheBContent": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "cripes"
},
{
"bitBText1": "crikey"
},
{
"bitBText1": "crimeny"
}
],
"visible": false
}
},
"extraNonsense": "bingoBlahBlah"
}
},
{
"contentItem": {
"content": {
"contentTypeB": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "jinkies"
},
{
"bitBText1": "ruh roh"
},
{
"bitBText1": "like, wow"
}
],
"visible": true
}
},
"extraNonsense": "bingoBlahBlah"
}
},
{
"contentItem": {
"content": {
"contentTypeC": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "cripes"
},
{
"bitBText1": "crikey"
},
{
"bitBText1": "crimeny"
}
],
"visible": true
}
},
"extraNonsense": "bingoBlahBlahBlah"
}
}
],
"myDadIsBetter": "Go Faster Stripes, innit."
}
},
"tabId": "Bro"
}
}
]
}
},
"levelOneC": "CAAQhGciEwi0iqD5-ZbwAhUBPvEFHQMKAeo=",
"levelOneD": {
"iAmJustHappyToBeNominated": "innit",
"damnYourWholePopCultureSubsection": "flames abound"
}
}
This is how you could solve this using object-scan
Note that I used quite a few ** in the matching. You could write these out exactly, it depends on your requirement
// const objectScan = require('object-scan');
const data = { levelOneA: { levelOneAArr: [{ name: 'me', age: 1 }, { name: 'you', age: 2 }, { name: 'them', age: 3 }], levelOneAText: 'blah' }, levelOneB: { levelOneBDeepBro: { levelOneBDeepBroTabs: [ { levelOneBDeepBroTabsShaper: { isBlessed: true, daContent: { daContentShaper: { contents: [ { contentItem: { content: { contentTypeA: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: true } }, extraNonsense: 'bingoBlah' } }, { contentItem: { content: { ahThisIsTheBContent: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: false } }, extraNonsense: 'bingoBlahBlah' } }, { contentItem: { content: { contentTypeB: { bitA: 'bitAText', bitB: [ { bitBText1: 'jinkies' }, { bitBText1: 'ruh roh' }, { bitBText1: 'like, wow' } ], visible: false } }, extraNonsense: 'bingoBlahBlah' } }, { contentItem: { content: { contentTypeC: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: false } }, extraNonsense: 'bingoBlahBlahBlah' } } ], myDadIsBetter: 'Go Faster Stripes, innit.' } }, tabId: 'Bro' } } ] } }, levelOneC: 'CAAQhGciEwi0iqD5-ZbwAhUBPvEFHQMKAeo=', levelOneD: { iAmJustHappyToBeNominated: 'innit', damnYourWholePopCultureSubsection: 'flames abound' } };
const logic = {
'levelOneB.**.daContentShaper.contents[*].*.content.{contentTypeA,ahThisIsTheBContent}': ({ key, parents }) => {
parents[3].splice(key[key.length - 4], 1);
},
'levelOneB.**.daContentShaper.contents.**.visible': ({ value, parent, property }) => {
if (value === false) {
parent[property] = true;
}
}
};
const modify = objectScan(Object.keys(logic), {
rtn: 'count',
filterFn: ({ matchedBy, property, key, value, parent, parents }) => {
matchedBy.forEach((m) => logic[m]({ property, key, value, parent, parents }));
}
});
console.log(modify(data));
// => 6
console.log(data);
// => { levelOneA: { levelOneAArr: [ { name: 'me', age: 1 }, { name: 'you', age: 2 }, { name: 'them', age: 3 } ], levelOneAText: 'blah' }, levelOneB: { levelOneBDeepBro: { levelOneBDeepBroTabs: [ { levelOneBDeepBroTabsShaper: { isBlessed: true, daContent: { daContentShaper: { contents: [ { contentItem: { content: { contentTypeB: { bitA: 'bitAText', bitB: [ { bitBText1: 'jinkies' }, { bitBText1: 'ruh roh' }, { bitBText1: 'like, wow' } ], visible: true } }, extraNonsense: 'bingoBlahBlah' } }, { contentItem: { content: { contentTypeC: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: true } }, extraNonsense: 'bingoBlahBlahBlah' } } ], myDadIsBetter: 'Go Faster Stripes, innit.' } }, tabId: 'Bro' } } ] } }, levelOneC: 'CAAQhGciEwi0iqD5-ZbwAhUBPvEFHQMKAeo=', levelOneD: { iAmJustHappyToBeNominated: 'innit', damnYourWholePopCultureSubsection: 'flames abound' } }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.3.0"></script>
Disclaimer: I'm the author of object-scan
Related
I have a [simplified] JSON file like
{
"id":87,
"meta_data":[
{
"id":1232,
"key":"user_created_by",
"value":"example#gmail.com"
},
{
"id":1233,
"key":"user_created_at",
"value":"1659890457477"
},
{
"id":1234,
"key":"good_person_or_silly_sausage",
"value":"No"
}
]
}
I want to do something like
Logger.log(orderDetailsObject.meta_data.value[key="good_person_or_silly_sausage"])
The expected value would be
No
However, this isn't what's occurring. At present I'm being told that the object is null.
I think it's because the meta_data object is an object in an object or two dimensional array or something? I don't have a good understand of what I'm doing here,
I feel like
https://docs.jsonata.org/simple
and
https://docs.jsonata.org/predicate
Should be guiding me towards the answer - but I'm not getting something I think.
I'm a newbie to SO and JSON & Javascript - so please be gentle. <3
EDIT: None-simplified actual json file below:
{
"id":87,
"parent_id":0,
"status":"pending",
"currency":"USD",
"version":"6.5.1",
"prices_include_tax":false,
"date_created":"2022-08-07T16:40:57",
"date_modified":"2022-08-11T10:13:07",
"discount_total":"0.00",
"discount_tax":"0.00",
"shipping_total":"0.00",
"shipping_tax":"0.00",
"cart_tax":"0.00",
"total":"1100.00",
"total_tax":"0.00",
"customer_id":17,
"order_key":"wc_order_omQo7nW5yCS9X",
"billing":{
"first_name":"",
"last_name":"",
"company":"",
"address_1":"",
"address_2":"",
"city":"",
"state":"",
"postcode":"",
"country":"",
"email":"freddie#example.com",
"phone":""
},
"shipping":{
"first_name":"",
"last_name":"",
"company":"",
"address_1":"",
"address_2":"",
"city":"",
"state":"",
"postcode":"",
"country":"",
"phone":""
},
"payment_method":"",
"payment_method_title":"",
"transaction_id":"",
"customer_ip_address":"",
"customer_user_agent":"",
"created_via":"rest-api",
"customer_note":"",
"date_completed":null,
"date_paid":"2022-08-07T16:40:58",
"cart_hash":"",
"number":"87",
"meta_data":[
{
"id":1232,
"key":"user_created_by",
"value":"example#gmail.com"
},
{
"id":1233,
"key":"user_created_at",
"value":"1659890457477"
},
{
"id":1234,
"key":"good_person_or_silly_sausage",
"value":"No"
},
{
"id":1235,
"key":"order_request_high_chair",
"value":"yes"
},
{
"id":1240,
"key":"order_notes",
"value":"They're on their honeymoon"
},
{
"id":1241,
"key":"pricing_notes",
"value":"They're on their honeymoon"
},
{
"id":1242,
"key":"order_booked_by",
"value":"me on me"
},
{
"id":1243,
"key":"order_referral_source",
"value":"Newspaper"
},
{
"id":1244,
"key":"commission_percent",
"value":"13"
},
{
"id":1245,
"key":"discount_percent",
"value":"5"
},
{
"id":1246,
"key":"deposit_paid_date",
"value":"today"
},
{
"id":1247,
"key":"damage_bond_date_paid",
"value":"today"
},
{
"id":1248,
"key":"damage_bond",
"value":"100"
},
{
"id":1249,
"key":"start_date",
"value":"01\/01\/01"
},
{
"id":1250,
"key":"deposit_payment_amount",
"value":"500"
},
{
"id":1251,
"key":"order_request_welcome_pack_wine_type",
"value":"Red"
},
{
"id":1252,
"key":"end_date",
"value":"02\/02\/02"
},
{
"id":1259,
"key":"_new_order_email_sent",
"value":"true"
},
{
"id":1260,
"key":"_automatewoo_order_created",
"value":"1"
}
],
"line_items":[
{
"id":45,
"name":"Villa Booking",
"product_id":0,
"variation_id":0,
"quantity":1,
"tax_class":"",
"subtotal":"1000.00",
"subtotal_tax":"0.00",
"total":"1000.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":411,
"key":"Dates",
"value":"01\/01\/01 until 02\/02\/02",
"display_key":"Dates",
"display_value":"01\/01\/01 until 02\/02\/02"
}
],
"sku":null,
"price":1000,
"parent_name":null
},
{
"id":46,
"name":"Standard Welcome Pack",
"product_id":73,
"variation_id":0,
"quantity":2,
"tax_class":"",
"subtotal":"0.00",
"subtotal_tax":"0.00",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":421,
"key":"Wine Type",
"value":"Red",
"display_key":"Wine Type",
"display_value":"Red"
}
],
"sku":"",
"price":0,
"parent_name":null
}
],
"tax_lines":[
],
"shipping_lines":[
],
"fee_lines":[
{
"id":47,
"name":"Damage Bond",
"tax_class":"",
"tax_status":"taxable",
"amount":"100",
"total":"100.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":428,
"key":"damage_bond_paid_to",
"value":"example#gmail.com",
"display_key":"damage_bond_paid_to",
"display_value":"example#gmail.com"
},
{
"id":429,
"key":"damage_bond_paid_on",
"value":"today",
"display_key":"damage_bond_paid_on",
"display_value":"today"
}
]
},
{
"id":48,
"name":"Booking Fee",
"tax_class":"",
"tax_status":"taxable",
"amount":"",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":436,
"key":"dbooing_fee_paid_to",
"value":"example#gmail.com",
"display_key":"dbooing_fee_paid_to",
"display_value":"example#gmail.com"
},
{
"id":437,
"key":"booking_fee_paid_on",
"value":"1659890457477",
"display_key":"booking_fee_paid_on",
"display_value":"1659890457477"
}
]
}
],
"coupon_lines":[
],
"refunds":[
],
"payment_url":"https:\/\/dev1.example.com\/checkout\/order-pay\/87\/?pay_for_order=true&key=wc_order_omQo7nW5yCS9X",
"date_created_gmt":"2022-08-07T16:40:57",
"date_modified_gmt":"2022-08-11T10:13:07",
"date_completed_gmt":null,
"date_paid_gmt":"2022-08-07T16:40:58",
"currency_symbol":"$",
"_links":{
"self":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/orders\/87"
}
],
"collection":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/orders"
}
],
"customer":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/customers\/17"
}
]
}
}
You can use the find method on the array:
const orderDetailsObject = {"id":87,"meta_data":[{"id":1232,"key":"user_created_by","value":"example#gmail.com"},{"id":1233,"key":"user_created_at","value":"1659890457477"},{"id":1234,"key":"good_person_or_silly_sausage","value":"No"}]};
console.log(orderDetailsObject.meta_data.find(
({key}) => key == "good_person_or_silly_sausage"
)?.value);
I'm trying to filter a data only "$match" user_data && seat_id I want use array that get in first "$match" in last pipeline "$match" after "$unwind" operator and I'm trying to do "$lookup" and find only matching element. my last "$match" aggregate not working last pipeline is to not working
---------this is my data----------
{
"user_id": {
"$oid": "62b048e762c6edd8b5d55b3e"
},
"ticketData": [
{
"seat_id": {
"$oid": "62b2098a9d03eb2e90ec089f"
}
},
{
"seat_id": {
"$oid": "62b2098a9d03eb2e90ec08a0"
}
},
{
"seat_id": {
"$oid": "62b2098a9d03eb2e90ec08a1"
}
}
],
"seat_status": true,
"createdAt": {
"$date": "2022-06-22T05:19:40.995Z"
}
}
this is the pipeline that I wrote
[
{
'$match': {
'user_id': new ObjectId('62b048e762c6edd8b5d55b3e')
}
}, {
'$lookup': {
'from': 'seats',
'localField': 'ticketData.seat_id',
'foreignField': 'show_seats.showByDate.shows.showSeats._id',
'as': 'seat_details'
}
}, {
'$unwind': {
'path': '$seat_details'
}
}, {
'$unwind': {
'path': '$seat_details.show_seats'
}
}, {
'$unwind': {
'path': '$seat_details.show_seats.showByDate.shows'
}
}, {
'$unwind': {
'path': '$seat_details.show_seats.showByDate.shows.showSeats'
}
}, {
'$match': {
'seat_details.show_seats.showByDate.shows.showSeats._id': {
'$in': 'ticketData.seat_id'
}
}
}
]
I have a array of version numbers looking like this:
[
{
"name": "v12.3.0.pre",
},
{
"name": "v12.2.5",
},
{
"name": "v12.2.4",
},
{
"name": "v12.2.3",
},
{
"name": "v12.2.1",
},
{
"name": "v12.2.0",
},
{
"name": "v12.2.0.pre",
},
{
"name": "v12.2.0-rc32",
},
{
"name": "v12.2.0-rc31",
},
{
"name": "v12.1.9",
},
{
"name": "v12.1.8",
},
{
"name": "v12.1.6",
},
{
"name": "v12.1.4",
},
{
"name": "v12.1.3",
},
{
"name": "v12.1.2",
},
{
"name": "v12.1.1",
},
{
"name": "v12.1.0",
},
{
"name": "v12.1.0.pre",
},
{
"name": "v12.1.0-rc23",
},
{
"name": "v12.1.0-rc22",
},
{
"name": "v12.0.9",
},
{
"name": "v12.0.8",
},
{
"name": "v12.0.6",
},
{
"name": "v12.0.4",
},
{
"name": "v12.0.3",
},
{
"name": "v12.0.2",
},
{
"name": "v12.0.1",
},
{
"name": "v12.0.0",
},
{
"name": "v11.12.0.pre",
},
{
"name": "v11.11.8",
}
]
From this array I would like to determine the latest version, which do not end with '.pre' or include 'rc.
I'm iterating through the array with a for-loop, and filtering out the '.pre' and 'rc' with an if statement. I then use split/join to remove the first 'v' character. So far so good.
Then I'm left with values like '12.2.5' and '11.12.10'. I first thought of removing the dots, then use a 'greater than' operator to see find the highest value, but then '11.12.10(111210)' would result greater than '12.2.5(1225)' which would not work out in my case.
for(i in arr){
if(!arr[i].name.endsWith('.pre') && !arr[i].name.includes('rc')){
var number = number.split('v').join("");
var number = number.split('.').join("");
}
}
Any ideas on best way to solve this? Thanks!
You could take String#localeCompare with options for getting a result.
var data = [{ name: "v12.3.0.pre" }, { name: "v12.2.5" }, { name: "v12.2.4" }, { name: "v12.2.3" }, { name: "v12.2.1" }, { name: "v12.2.0" }, { name: "v12.2.0.pre" }, { name: "v12.2.0-rc32" }, { name: "v12.2.0-rc31" }, { name: "v12.1.9" }, { name: "v12.1.8" }, { name: "v12.1.6" }, { name: "v12.1.4" }, { name: "v12.1.3" }, { name: "v12.1.2" }, { name: "v12.1.1" }, { name: "v12.1.0" }, { name: "v12.1.0.pre" }, { name: "v12.1.0-rc23" }, { name: "v12.1.0-rc22" }, { name: "v12.0.9" }, { name: "v12.0.8" }, { name: "v12.0.6" }, { name: "v12.0.4" }, { name: "v12.0.3" }, { name: "v12.0.2" }, { name: "v12.0.1" }, { name: "v12.0.0" }, { name: "v11.12.0.pre" }, { name: "v11.11.8" }],
highest = data
.filter(({ name }) => !name.endsWith('.pre') && !name.includes('rc'))
.reduce((a, b) =>
0 < a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' })
? a
: b
);
console.log(highest);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think i have a solution for you: Save the numbers to arrays, so you have for the numbers '12.2.5' and '11.12.10' the following:
[12,2,5] and [11,12,10]
Then you compare the arrays. Keep the greates from the [0] position, if they're equal the greates from the [1] position and so...
Maybe it works...
Hope it helps you!!
Kind regards,
Sergio.
Here I am not going with the logic of removing and filtering out the '.pre' and 'rc' with an if statement. then use split/join to remove the first 'v' character. Then you left with the values like '11.12.10' and '12.2.5' so, after getting these values you can use below code
You could prepend all parts to fixed-size strings, then sort that, and finally remove the padding again
Below code, the snippet is an example not for above exactly but will help you sure
var arr = ['12.2.5', '11.12.10', '12.0.6', '6.1.0', '5.1.0', '4.5.0'];
arr = arr.map( a => a.split('.').map( n => +n+100000 ).join('.') ).sort()
.map( a => a.split('.').map( n => +n-100000 ).join('.') );
console.log(arr)
The basic idea to make this comparison would be to use Array.split to get arrays of parts from the input strings and then compare pairs of parts from the two arrays; if the parts are not equal we know which version is smaller. Reference
var versionsList = [
{ "name": "v12.3.0.pre" },
{ "name": "v12.2.5" },
{ "name": "v12.2.4" },
{ "name": "v12.2.3" },
{ "name": "v12.2.1" },
{ "name": "v12.2.0" },
{ "name": "v12.2.0.pre" },
{ "name": "v12.2.0-rc32" },
{ "name": "v12.2.0-rc31" },
{ "name": "v12.1.9" },
{ "name": "v12.1.8" },
{ "name": "v12.1.6" },
{ "name": "v12.1.4" },
{ "name": "v12.1.3" },
{ "name": "v12.1.2" },
{ "name": "v12.1.1" },
{ "name": "v12.1.0" },
{ "name": "v12.1.0.pre" },
{ "name": "v12.1.0-rc23" },
{ "name": "v12.1.0-rc22" },
{ "name": "v12.0.9", },
{ "name": "v12.0.8", },
{ "name": "v12.0.6", },
{ "name": "v12.0.4", },
{ "name": "v12.0.3", },
{ "name": "v12.0.2", },
{ "name": "v12.0.1", },
{ "name": "v12.0.0", },
{ "name": "v11.12.0.pre", },
{ "name": "v11.11.8", }
];
function versionCompare(v1, v2) {
var v1parts = v1.split('.'),
v2parts = v2.split('.');
for (var i=0; i<v1parts.length; i++) {
if (v1parts[i] === v2parts[i]) {
continue;
}
else if (v1parts[i] > v2parts[i]) {
return v1;
}
else {
return v2;
}
}
return v1;
}
var maxVersion;
for (i in versionsList) {
version = versionsList[i].name;
if (!version.endsWith('.pre') && !version.includes('rc')) {
if (typeof maxVersion === "undefined")
maxVersion = version.substr(1);
var ver = version.substr(1);
if (ver !== maxVersion)
maxVersion = versionCompare(ver, maxVersion);
}
}
console.log('v'+ maxVersion);
I'm trying to filter this objects array and keep the original one aside.
{"departments":
[
{
“name": “AAA",
“selected”: true,
"courses": [
{
"name": “course1",
“selected”: true,
“titles”:
[{
"name": “title1",
“selected”: true
},
{
"name": “title2",
“selected”: false
}]
},
{
"name": “course2",
“selected”: false,
“titles”:
[{
"name": “title1",
“selected”: false
}]
}
]
},
{
“name": “BBB",
“selected”: false,
"courses": [{...}]
{...}
]
}
I want to find all the selected departments, courses and titles. And it should be in the same format.
I tried with below code, but it change original data. I want to keep that aside too.
const depts = departments.filter((dept: any) => {
if (dept.selected) {
dept.courses = dept.courses.filter((course: any) => {
if (course.selected) {
if (course.titles) {
course.titles = course.titles.filter(({selected}: any) => selected);
}
return true;
}
return false;
});
return true;
}
return false;
});
What would be considered the best solution in this case?
Shorter alternative can be to use the JSON.parse reviver parameter :
var arr = [{ name: "AAA", selected: true, courses: [{name: "course1", selected: true, titles: [{ name: "title1", selected: true }, { name: "title1", selected: false }]}, { name: "course2", selected: false, titles: [{ name: "title1", selected: false }]}]}]
var result = JSON.parse(JSON.stringify(arr), (k, v) => v.map ? v.filter(x => x.selected) : v)
console.log( result )
your filtering logic seems to be correct. only problem is that code changes original array. in order to overcome this problem just create a deep clone of original array and run filtering logic on it
filterArray() {
const clone = JSON.parse(JSON.stringify(this.departments));
const depts = clone.filter((dept: any) => {
if (dept.selected) {
dept.courses = dept.courses.filter((course: any) => {
if (course.selected) {
if (course.titles) {
course.titles = course.titles.filter(({ selected }: any) => selected);
}
return true;
}
return false;
});
return true;
}
return false;
});
console.log(depts);
}
here is a demo https://stackblitz.com/edit/angular-xx1kp4
const filterSelected = obj => {
return {
...obj,
departments: obj.departments.map(dep => {
return {
...dep,
courses: dep.courses.map(course => {
return {
...course,
titles: course.titles.filter(title => title.selected),
};
}).filter(course => course.selected),
};
}).filter(dep => dep.selected),
};
}
const all = {
departments: [
{
name: "AAA",
selected: true,
courses: [
{
name: "course1",
selected: true,
titles: [
{
name: "title1",
selected: true
}, {
name: "title1",
selected: false
}
]
}, {
name: "course2",
selected: false,
titles: [
{
name: "title1",
selected: false
}
]
},
]
}
]
};
console.log(filterSelected(all));
I don't know if you prefer an API false. Here is my tip:
You can to use an API Json Server.
Install JSON Server
npm install -g json-server
Create a db.json file with some data
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
Start JSON Server
json-server --watch db.json
Now if you go to http://localhost:3000/posts/1, you'll get
{ "id": 1, "title": "json-server", "author": "typicode" }
you can search your array of objects using various shapes and it will come filtered. More about the API here: https://github.com/typicode/json-server
(Use a filter to do your searches on the Angular, it will bring you right what you need, use a method inside your component)
Im wondering how I can grab and then display in my html file(using pure Javascript) the following objects found in the below JSON file? I specifically need to grab the following 3 objects and display each instance of each.. "barTitle," "id," and show all "OpenTimes."
Please note, I do have this file already uploaded to a webserver(http://codepupil.com/js/bar.json).
onBarLocationsLoaded({
"results":[
{
"barCity":"Annapolis",
"barState":"MD",
"barZip":"21401",
"recordingPhone":"410-213-1145",
"distance":"2.10",
"longitude":-725464,
"latitude":489914,
"barLong":-725464,
"barLat":489914,
"barLink":"http:\/\/www.bar.com\/bar\/bow-tie",
"barName":"Bow Tie Bar",
"movie":[
{
"barTitle":"Bar Louie",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Louise",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Louie",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Capo",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Boo Boo",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
}
]
});
This is a function call with a big ass parameter
For example
function launchAnAlert(message) {
alert(message);
}
This a js function that take a parameter named message and does something with it.
and if you want to call that function you do it like this
launchAnAlert("This is my text message");
Now let's take a look at your snippet, as you can see it looks like the previous call but instead of a String you are passing a Json object as parameter.
Your function name is onBarLocationsLoaded , in that snippet of yours is of this form
onBarLocationsLoaded(theJsonObject);
And there is an error in that Json object.
You Json file should contain this :
{
"results":[
{
"barCity":"Annapolis",
"barState":"MD",
"barZip":"21401",
"recordingPhone":"410-213-1145",
"distance":"2.10",
"longitude":-725464,
"latitude":489914,
"barLong":-725464,
"barLat":489914,
"barLink":"http:\/\/www.bar.com\/bar\/bow-tie",
"barName":"Bow Tie Bar",
"movie":[
{
"barTitle":"Bar Louie",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Louise",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Louie",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Capo",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
},
{
"barTitle":"Bar Boo Boo",
"Id":"20057095",
"openTimes":[
{
"time":"12:00pm"
},
{
"time":"3:40pm"
},
{
"time":"6:40pm"
}
]
}
]
}
]
}
Now if you use the answer you can find here : https://stackoverflow.com/a/7220510/4088809
This should answer your question or at least point you in the direction : http://jsfiddle.net/hrncdj8e/