JSON from website with “pure” JavaScript > exract and put into variables

I want to create a new Scriptable widget for iOS, showing a so called “blood groups barometer”, meaning the current status of blood reserves at the German Red Cross.

I have found this website, where the status is given in the source code, in the form of JSON:

<script type="application/json" data-drupal-selector="drupal-settings-json">
{"path":{"baseUrl":"/","scriptPath":null,"pathPrefix":"","currentPath":"node/3","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"de"},"pluralDelimiter":"u0003","blutgruppen":{"default":{"blood_barometer_a_plus":"1","blood_barometer_b_plus":"2","blood_barometer_ab_plus":"4","blood_barometer_zero_plus":"2","blood_barometer_a_neg":"1","blood_barometer_b_neg":"1","blood_barometer_ab_neg":"2","blood_barometer_zero_neg":"1"},"blood_barometer_changed":"2022-04-22"},"user":{"uid":0,"permissionsHash":"09f524fbefd35c1e3e7cc2b74fe2992115d7821527911825e868534003f88b7a"}}
</script>

Formatted into a readable JSON format:

{
   "path":{
      "baseUrl":"/",
      "scriptPath":null,
      "pathPrefix":"",
      "currentPath":"node/3",
      "currentPathIsAdmin":false,
      "isFront":false,
      "currentLanguage":"de"
   },
   "pluralDelimiter":"u0003",
   "blutgruppen":{
      "default":{
         "blood_barometer_a_plus":"1",
         "blood_barometer_b_plus":"2",
         "blood_barometer_ab_plus":"4",
         "blood_barometer_zero_plus":"2",
         "blood_barometer_a_neg":"1",
         "blood_barometer_b_neg":"1",
         "blood_barometer_ab_neg":"2",
         "blood_barometer_zero_neg":"1"
      },
      "blood_barometer_changed":"2022-04-22"
   },
   "user":{
      "uid":0,
      "permissionsHash":"09f524fbefd35c1e3e7cc2b74fe2992115d7821527911825e868534003f88b7a"
   }
}

From that, I want to read the following values into JS variables:

   "blutgruppen":{
      "default":{
         "blood_barometer_a_plus":"1",
         "blood_barometer_b_plus":"2",
         "blood_barometer_ab_plus":"4",
         "blood_barometer_zero_plus":"2",
         "blood_barometer_a_neg":"1",
         "blood_barometer_b_neg":"1",
         "blood_barometer_ab_neg":"2",
         "blood_barometer_zero_neg":"1"
      },
      "blood_barometer_changed":"2022-04-22"
   }

The point is, that Scriptable is not working with jQuery, so I cannot use the following script, which is linked on the above mentioned website (extract):

    jQuery('.blutbeutel-wrapper').each(function () {
      let bestand = drupalSettings.blutgruppen.default[jQuery(this).data('id')];
      var prozent = 11 + (12 * bestand);
      jQuery(this).find('.blut').css({'height': prozent + '%'});
      animationDone = true;
    });

Any hints, how I can
a) read the JSON with “pure JS” from the website’s source code and
b) extract its values into variables?

can’t fix ExpressPeerServer is not a function in server.js

I am stuck in a error where I have successfully installed peer.js library in my npm project but in my server.js file, when I try to import peer library and use it as a function, it is saying that peerServer is not a function.

const express = require('express');
const app = express()
const server = require("http").Server(app);
const {v4:uuidv4} = require("uuid")
const io = require("socket.io")(server);
const peerServer = require("peer");
const ExpressPeerServer = peerServer(server, {
    debug: true,
})

app.use(express.static('public'));
app.set('view engine', 'ejs');

app.get("/", (req, res)=>{
    res.redirect(`/${uuidv4()}`)
})
app.get('/:room', (req, res)=>{
   res.render('room', {roomId : req.params.room})
})

server.listen(3000, ()=>{
    console.log("Server is running on port 3000")
})

enter image description here

Published ES modules in an npm package, can’t import

I’m trying to use an npm package that I published. I have it installed and the files are present and up to date in node_modules, but when I try to import it like so:

import Message from 'discord-helper-lib';

I get the following error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find package
‘C:pathtocodenode_modulesdiscord-helper-lib’ imported from
C:pathtocodeapiGameUpdater.js

The package itself has the following package.json:

{
    "name": "discord-helper-lib",
    "version": "2.0.2",
    "description": "Discord Helper Library",
    "type": "module",
    "scripts": {},
    "dependencies": {
        "emoji-regex": "^9.2.2"
    }
}

and the class I’m trying to import is defined as follows:

export default class Message {
    constructor(text, messageReplyDetails) {
           //..
    }
}

Is there anything else I have to do to set up a module as an npm package to import it like others? Not sure if there’s configuration or other requirements4

State array not updating when removing an array item – ReactJS

When i remove an array item from my state array, I am also updating the prices after removing the array item. But prices are not updating. I have tried every thing, but didn’t get any solution.

export default function CustomizerState(props) {
    const initialTextItem = {
        text: "Hello",
        neonPrice: 0,
        backplatePrice: 0,
        neonPower: 0,
        totalPrice: 0
    }
    const [settings, setSettings] = useState({
        textItems: [initialTextItem],
        libraryItems: [],
        accessories: [
            {
                name: "Power Supply",
                quantity: 1,
                unitPrice: 10
            },
            {
                name: "UK Plug",
                quantity: 1,
                unitPrice: 3
            },
            {
                name: "Dimmer",
                quantity: 1,
                unitPrice: 10
            }
        ],
        finalPrice: null
    })

    const removeItem = (id, itemType = "textItems") => {
        const filteredItems = settings[itemType].filter((item) => {
            return item.id !== id
        })
        setSettings((prevState) => (
            {...prevState, [itemType]: filteredItems}
        ))
        finalPrice()
    }

    const finalPrice = () => {
        const textItemsPrice = getTotalPrice()
        const libraryItemsPrice = getTotalPrice("libraryItems")
        const accessoriesPrice = getTotalPrice("accessories", "unitPrice")
        console.log(textItemsPrice, libraryItemsPrice, accessoriesPrice)

        const finalPrice = textItemsPrice + libraryItemsPrice + parseInt(accessoriesPrice)
        setSettings((prevState) => (
            {...prevState, finalPrice}
        ))
    }

    const getTotalPrice = (itemType = "textItems", priceKey = "totalPrice") => {
        let price = 0
        settings[itemType].map((item) => (
            price = price + (item[priceKey] * item.quantity)
        ))
        return price
    }

    return (
        <CustomizerContext.Provider value={{settings, addTextItem,
            removeItem}}>
            {props.children}
        </CustomizerContext.Provider>
    )
}

For now, it is behaving like when i remove any item, it doesn’t update the finalPrice object item, but when i remove another item then it updates the prices for previous items. I don’t know why it is behaving like this. Can someone please have a look on my code and tell me what is wrong with it and how can i fix this?

React Grid List Component PreSelect?

I have this function in my home.jsx:

function GridListComponent(options) {
    return (
        <li>
            <input type="checkbox" id={options.id} />
            <label htmlFor={options.id}>{options.tileInfo}</label>
        </li>
    );
}

function Home() {
    return (
        <div className="home">
            <div class="container">
                <div class="row align-items-center my-5">
                    <div class="col-lg-12">
                        <h1 class="font-weight-light">Site Setting</h1>
                        <p>Pillar Selection:</p>
                    </div>
                    <ul className="grid">
                        <GridListComponent id="grid-opt-1" tileInfo="A" />
                        <GridListComponent id="grid-opt-2" tileInfo="B" />
                        <GridListComponent id="grid-opt-3" tileInfo="C" />
                        <GridListComponent id="grid-opt-4" tileInfo="D" />
                    </ul>
                </div>
            </div>
      <hr />
        </div>
    
    
    );
}

And it works fine. All I need is to pre-select 1 or 2 options.
Currently, once the page loads, I see this:
pageLoads

And here is what happens when click:
pre-select

so All I need is to have A and C pre-selected.

save the dark mode and light mode button

Hello I would like to make a localstorage for my darkmode button on my site but I do not know how to take me here is the current code

codepen

        
  const chk = document.getElementById('chk');

  chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
    localStorage.setItem('dark', 'chk');
    
  });

Extract original JavaScript Code from Bookmarklet

I have a bookmarklet, that I use regularly.
I’d like to utilize the JavaScript Code from the Bookmarklet in the Apple Shortcuts App.

Any way to extract the code from this Bookmarklet, to get JavaScript compliant Code?

What I am trying to achieve is:

  • Pass URL to Shortcut
  • Work with that URL to shorten it with the JavaScript Code

The Bookmarklet:

javascript:(function()%7Bvar%20d=false;%20var%20n_u=navigator.userAgent;%20if(location.protocol=='https:'%20&&%20(n_u.indexOf('Chrome')!=-1%20%7C%7C%20n_u.indexOf('Opera')!=-1))%7Bwindow.open('https://t1p.de/?url='+encodeURIComponent(document.URL.replace('+',%20'%2B')),%20'_blank');%20d=true;%7D%20if(!d)%7Bvar%20d=document,s=d.createElement('script');s.charset='UTF-8';s.type='text/javascript';s.src='https://t1p.de/js/bookmark.php?s=0.3&url='+encodeURIComponent(d.URL);d.body.appendChild(s);%7D%7D)();

Add all objects with the same id from one array into an array of an object with the same id in another array

I have 2 arrays. I need to move all the objects that have the same id in arraySecondary into an array inside an object with the same id in arrayPrimary.

Example:

    const arrayPrimary = [
      { "id": "1", "location": "France", "price": "12,3" },
      { "id": "2", "location": "Germany", "price": "12,0" },
      { "id": "3", "location": "USA", "price": "10" },
      { "id": "4", "location": "Italy", "price": "16" },
    ];

    const arraySecondary = [
      { "id": "1", "name": "phil", "location": "New York", "price": "1,3", "dd": "lql" },
      { "id": "2", "location": "Paris", "dd": "lql" },
      { "id": "3", "location": "Egypt" },
      { "id": "2", "name": "joe", "location": "London" },
      { "id": "1", "location": "location", "name": "april" },
      { "id": "2", "name": "mei", "location": "Barcelona" },
    ];

Expected result:

    [
      {
        id: 1,
        location: "France",
        price: "12,3",
        area: [
          { id: 1, location: "location", name: "april" },
          { id: 1, name: "phil", location: "New York", price: "1,3", dd: "lql" },
        ],
      },
      {
        id: 2,
        location: "Germany",
        price: "12,0",
        area: [
          { id: 2, location: "Paris", dd: "lql" },
          { id: 2, name: "joe", location: "London" },
          { id: 2, name: "mei", location: "Barcelona" },
        ],
      },
      { id: 3, location: "USA", price: 10, area: [{ id: 3, location: "Egypt" }] },
      { id: 4, location: "Italy", price: 16 },
    ];
    //or json

First i add an empty array to each object in arrayPrimary.

 arrayPrimary.map((v) => ({ ...v, area: [] }));

After that i filter arraySecondary by id and push all the results into area array in each object in arrayPrimary. But here i get stuck.

    console.log(
      arrayMain.forEach((main) =>
        main.area.push(arrayItems.filter((items) => items.id === main.id))
      )
    );

Second idea is to first order each object in arraySecondary by id and then push that into empty area array in arrayPrimary

let op = arrayItems.reduce((op,inp) => {
  op[inp.id] = op[inp.id] || []
  op[inp.id].push(inp)
  return op
},{})

console.log(op)

And this is where i am stuck with both ideas.

Material Ui Rating wrapping long values

i’m currently trying to work around the material ui rating component and how to do a flex wrap if the icons overflow the with of the parent component.

If i try to add flex-wrap: wrap to the rating component, it actually wraps the icons but the interactive functionality stops working pas the first line.

There is a code example below to better demonstrate this.

Code Example in codesandbox

Is there a way to make it work with flex wrap?

If anyone could help i will very much appreciate

how to retrieve the object from array of objects and arrays using javascript

I have array of objects and arrays.

If the array of objects has value property same

  • and if place includes of arrraylist list return first obj

  • and if place is equal includes/not includes return first obj

if no above conditions return undefined; using javascript

var list=['SG','TH','MY']


var arrobj1=[
  {id:1, name:'userone',place:'SG', value:100},
  {id:2, name:'usertwo',place:'TH', value:100},
  {id:3, name:'userthree',place:'IL',value:200},
]
Expected Output
{id:1, name:'userone',place:'SG', value:100}

****
var arrobj2=[
  {id:1, name:'userone',place:'IN', value: 200},
  {id:2, name:'usertwo',place:'SL',value: 100},
  {id:3, name:'userthree',place:'SL', value: 100},
]
Expected Output
{id:2, name:'usertwo',place:'SL',value: 100}
****
var arrobj3=[
  {id:1, name:'userone',place:'SL', value:10},
  {id:2, name:'usertwo',place:'IN', value:20},
  {id:3, name:'userthree',place:'KL', value:30},
]
Expected Output
undefined

Tried

var result= arrobj.find(e=>{
  if((e.value === e.value) && (list.includes(e.place)){
   return e
  }
})