startsWith only working for first condition

Im having a bit of an issue and im not sure where I am going wrong.
I have a Map which is bringin in prices, based on the ID of the product I need to add a discount or skip it.

                    let discountPrice = !prod.ProductID.startsWith('BGM', 'S11', 'BGP') && prod.CurrentPrice.toString().endsWith('97') ? parseFloat(prod.CurrentPrice) * 0.05 : !prod.ProductID.startsWith('BGM', 'S11', 'BGP') ? parseFloat(prod.CurrentPrice) * 0.15 : 0
                    let dp =  usdNumber.format( discountPrice )
                    let finalPrice = parseFloat(prod.CurrentPrice) - parseFloat(discountPrice)
                    let totalWithQ = finalPrice * prod.Quantity
                    let fp =  usdNumber.format( totalWithQ )

This works great for BGM it will skip the discount but for S11 and BGP it will still apply the discount where if the product ID has BGM, S11 or BGP i want it to skip.

results

Am I using startsWith wrong? Can it not pass multiple things through it and have it loop through per argument?

    {User?.Cart && User?.Cart.length > 0 && (
            <>
              <Table>
                <Thead>
                  <Tr className="text-left border-b-2 border-blue">
                    <Th className="py-5">Product</Th>
                    <Th className="py-5">Price</Th>
                    <Th className="py-5">Overstock Discount Per Item</Th>
                    <Th className="py-5">Quantity</Th>
                    <Th className="py-5">Total Price</Th>
                    <Th className="py-5">Controls</Th>
                  </Tr>
                </Thead>
                <Tbody>
                  {User.Cart.map((prod, i) => {
                    let discountPrice = !prod.ProductID.startsWith('BGM', 'S11', 'BGP') && prod.CurrentPrice.toString().endsWith('97') ? parseFloat(prod.CurrentPrice) * 0.05 : !prod.ProductID.startsWith('BGM', 'S11', 'BGP') ? parseFloat(prod.CurrentPrice) * 0.15 : 0
                    let dp =  usdNumber.format( discountPrice )
                    let finalPrice = parseFloat(prod.CurrentPrice) - parseFloat(discountPrice)
                    let totalWithQ = finalPrice * prod.Quantity
                    let fp =  usdNumber.format( totalWithQ )
                    return (
                      <Tr
                        key={`key-cart-prod-${i}`}
                        className="border-b border-opacity-50 border-Blue"
                      >
                        <Td className="py-5">
                          <Link href={`/product/${prod.Slug}`}>
                            <a>
                              {`${prod.Description} (${prod.ProductID})`}
                            </a>
                          </Link>
                        </Td>
                        <Td className="py-5">{`$${prod.CurrentPrice}`}</Td>
                        <Td className="py-5">{`${dp}`}</Td>
                        <Td className="py-5">{`Qty: ${prod.Quantity}`}</Td>
                        <Td className="py-5">{`${fp}`}</Td>
                        <Td className="py-5" style={{width: '1%', whiteSpace: 'nowrap'}}>
                          <RemoveFromCart ProductID={prod.ProductID} />
                        </Td>
                      </Tr>
                    )
                  })}
                </Tbody>

How to append only node’s child nodes?

Assuming the following node(s) (which is/are actually not generated like this):

let outer = document.createElement('div');
outer.innerHTML = `
  <div>foo</div>
  <div>bar</div>
  .
  .
  .
  <div>whatever</div>
`;

Now I can append outer to another node:

let body = document.querySelector('body');
body.append(outer);

But how to append only the inner of outer without loosing event listeners etc.?

reason why clearInterval doesnt stop the execution of setInterval function [duplicate]

I’m trying to use clearInterval (when clicking on “stop” <li> with id="li2"), to stop y – to which setInterval is assigned to (triggered by start <li> with id="li1").

  1. I don’t understand why every time I click on “stop”, y stops and fires again.
  2. How to make clearInterval work as intendent? (stop y without re-firing) (suppose it would have to be scoped differently)
//cons
const li1 = document.getElementById("li1")
const li2 = document.getElementById("li2")

//el
li1.addEventListener("click", slideShowAbstract)
li2.addEventListener("click", slideShowAbstract)

//f
function slideShowAbstract(e) {

  if (e.target.id === "li1") {
    console.log("play")
    var y = setInterval(() => console.log("playing"), 2000)
  }

  if (e.target.id === "li2") {
    console.log("stop")
    clearInterval(y)
  }
}
ul {
  display: flex;
  justify-content: center;
  list-style-type: none;
}

li:hover {
  cursor: pointer;
}
<ul>
  <li id="li1">play</li>
  <li id="li2">stop</li>
</ul>

why i can’t connect javascript with firebase?

I tried to connect my javascript app with firebase, I created an account in firebase, I pasted my configuration, but it gives me 3 errors:

Unexpected token ‘export’;

Cannot use import statement outside a module;

firebase is not defined

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <script src="https://www.gstatic.com/firebasejs/9.8.3/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.8.3/firebase-firestore.js"></script>

    <script type="module">
        // Import the functions you need from the SDKs you need
        import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-app.js";
        // TODO: Add SDKs for Firebase products that you want to use
        // https://firebase.google.com/docs/web/setup#available-libraries
      
        // Your web app's Firebase configuration
        const firebaseConfig = {
          apiKey: "<key>",
          authDomain: "javascript-3bbaa.firebaseapp.com",
          projectId: "javascript-3bbaa",
          storageBucket: "javascript-3bbaa.appspot.com",
          messagingSenderId: "<id>",
          appId: "<appId>"
        };
      
        // Initialize Firebase
        const app = initializeApp(firebaseConfig);
        const db = firebase.firestore();
      </script>
    
</body>
</html>

Select certain attributes from a document in mongodb using mongoose for dynamic referencing

Is it possible to select certain attributes from an object? for example excluding an email, logoUri…etc and personal info from a seller when populating dynamically?

Here is my messageSchema:

const messageSchema = mongoose.Schema({
  chatId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "Chat",
  },
   ....
  // sender can be type of User or Seller
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    refPath: "senderType",
    required: true,
  },
  senderType: {
    type: String,
    required: true,
    enum: ["User", "Seller"],
  },
  readOn: { type: Date },
  read: Boolean, //}, {
  sentOn: {
    type: Date,
    default: Date.now,
  },
});

here is where I populate my schema:

const messages = await Message.find({ chatId: chatId })
      .populate("sender")
      .sort({
        sentOn: -1,
      });

since each has different attribute, is there a way to select depending on the type of model I am populating dynamically ? For example for user model:

.select('-email -logoUri') 

for seller model:

.select('-address')

Referring JSON keys that are numbers [duplicate]

My JSON data stored in dataTest.json data goes as follows :

    "1":"value1",
    "2":"value2"
}

The above gives positive results in a validator.

Now if I want to use this data in a javascript program like

var data = require('./dataTest.json');
console.log(data.1)

I get an error saying

console.log(data.1)
            ^^^^^^^^^
SyntaxError: missing ) after argument list

But simply changing the first key to something like a1 instead of simply 1 and calling it like data.a1 fixes it.

For several reasons, I’d like to keep the keys as simple numbers. Is there any way to refer to such keys with numerical values?

Node not working/running Javascript code in terminal

I have deleted and reinstalled nodejs. I have also checked the system path files to ensure it is their.
In my vscode, when I type node -v it shows the version. However, when I try to run my Javascript file and type node deploy.js or node .deploy.js it does not show the output or run the file.

I have even tried this on cmd but same issue. Node is not running my javascript code nor is it showing any error messages. How can I fix this to ensure I can run my javascript code in the terminal? Please advice, I have been stuck over this for way too long.

enter image description here

How to add css property to a span tag of an innerhtml

I have a innerhtml

Lets say

<p>
<span>8218819999</span>
<span>hello</span>
</p>

I want add css property for first span tag

How can I do that ??
Using jquery or javascript.

This whole html is coming from AEM Label which I don’t have control over.

Using ngafterviewinit I’m getting the innerhtml
But not sure how to update the css.

Out of sync state and view

Facing a strange issue with the latest stable releases of Nextjs and React, where state and view updates are out-of-sync.

import { useState, useMemo } from "react";

const items = [
  { id: 1, name: "apple" },
  { id: 2, name: "orange" },
  { id: 3, name: "mango" }
];

export default function IndexPage() {
  const [desc, setDesc] = useState(true);

  const sortedItems = useMemo(() => [...(desc ? items : items.reverse())], [
    desc
  ]);

  return (
    <div>
      <button onClick={() => setDesc((s) => !s)}>change order</button>
      <br />
      <span>desc: {desc.toString()}</span>
      <pre>{JSON.stringify(sortedItems, null, 2)}</pre>
    </div>
  );
}

Package versions:

"next": "12.1.6",
"react": "18.2.0",
"react-dom": "18.2.0",

As you can see from the output below, array elements are not updated on the view front based on the current sort state. Multiple clicks are required to do so.

Is this a random bug or am I fooling myself!?

CodeSandbox

Output

Inserting variables into JSON data

I’m using https://github.com/jerosoler/Drawflow plugin, but I’m trying to add a few variables to the strings written below, but I can’t.

var data= {
    "drawflow": {
        "Home": {
            "data": {}
        },
        "Other": {
            "data": {
                "16": {
                    "id": 16,
                    "name": "Michael",
                    "data": {},
                    "class": "michael"                  
                }                
            }
        }
    }
}

i want to do but I can’t add my variables is there any other way;
Unexpected token gives ‘+’ error when I add it as “‘” + variable+ “‘”

var int= 2;
var string="car";

"data": {
                int: {
                    "id": int,
                    "name": string,
                    "data": {},
                    "class": string,                
                    "inputs": {}
                }

jsPlumb make connectors editable with EditableFlowchart

I’ve been digging for a few days to develop a flowchar with connector editalbe, something like the picture below.
In the documentation it says that I need another package – jsplumbtoolkit-editable-connectors and then to declare it as a dependency. However, I can’t find it on npm and I don’t know how to do that.

"dependencies:{
 ...
 "jsplumbtoolkit-editable-connectors":"file:./path/to/jsplumbtoolkit-editable-connectors.tgz"
 ...
}

image from documentation

jsPlumb Community 2.xx

Filter array of objects and remove object is filter returns empty values

Here is my question. I have an array of objects as shown below. Each object has a title and rows in it. rows is also array of objects with risk values like P1, P2, P3 etc. I want to filter and get only those rows whose risk is equal to P1. In some objects, there might be no risk with P1 at all. In that case, i want to ignore that object completely.

let data = [ 
    {
        "title": "QA",
        "rows": [
            {
                "risk": "P3",
                "Title": "Permission issue",
            }
        ]
    }, 
    {
        "title": "Prod",
        "rows": [
            {
                "risk": "P5",
                "Title": "Console log errors fix",
            },
            {
                "risk": "P1",
                "Title": "Server is in hung state",
            }
        ]
    }
]

I want the result as follows. As you can see the title QA didnt have P1 at all. so i want to ignore that object as a whole.

    {
        "title": "Prod",
        "rows": [
            {
                "risk": "P1",
                "Title": "Server is in hung state",
            }
        ]
    }
]

I tried using this code. but the problem with this is that the title with QA gets added in the final output even though it doesnot have any P1 risk in it.

let result = input.map((obj) => ({
  ...obj,
  rows: obj.rows.filter((row) => row.risk === "P1"),
}));

Can someone let me know how to filter the objects with P1 and skip the whole object if there are no P1 in it.

Using JQuery load method to render component inside a div. How to render multiple components in divs

This is the code i am using, unable to render components in div with same class name.
but its strange, if i am using divs, one with id and one with class. its rendering fine. but if i add the 3rd one. its not rendering. 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>React App</title>

function renderComponent(id){
$(document).ready(function () {
$(id).load(
“private component url link”
); // Handler for .ready() called.
});
}

//renderComponent(“#a”)
renderComponent(“#d”)
renderComponent(“.team-container”)