How can I get the corresponding price from my feed based on my product name?

For my affiliate site I import a XML feed and then use the XML2JSON function to convert this to a JSON object. It looks like this:

{products: {…}}
products:
product: Array(6510)
[0 … 99]
0:
aw_deep_link: "https://www.awin1.com/pclick.php?p=21982055441&a=852189&m=12893"
aw_image_url: "https://images2.productserve.com/?w=200&h=200&bg=white&trim=5&t=letterbox&url=ssl%3Awww.spellenrijk.nl%2Fresize%2F18111_3wy7yf3_5638761353075.jpg%2F300%2F300%2FTrue%2Fblackfire-boardgame-sleeves-square-72x73mm.jpg&feedId=25919&k=1ab7328112246a7b95251ed47642ace5169a9583"
aw_product_id: "21982055441"
category_id: "0"
category_name: ""
currency: "EUR"
data_feed_id: "25919"
delivery_cost: "3,99"
description: "Bordspel sleeves met een afmeting van 72 x 73 mm. Deze verpakking bevat 100 sleeves. Geschikt voor: Catan card game, Anno 1701 card game, Summertime, Powergrid, Funkenschlag vele andere spellen. - Thickness 40 microns - Extra high clarity - Prevents bent corners - Prevents scratches - Perfect fitting for a lot of board game cards - Durable material for long gameplay - Acid free - no PVC"
display_price: "EUR2.95"
language: ""
last_updated: ""
merchant_category: "Spelonderdelen"
merchant_deep_link: "https://www.spellenrijk.nl/artikel/20343/blackfire-boardgame-sleeves-square-72x73mm.html?utm_source=affiliate4you-NL&utm_campaign=datafeed"
merchant_id: "12893"
merchant_image_url: "https://www.spellenrijk.nl/resize/18111_3wy7yf3_5638761353075.jpg/300/300/True/blackfire-boardgame-sleeves-square-72x73mm.jpg"
merchant_name: "Spellenrijk.nl NL - FamilyBlend"
merchant_product_id: "20343"
product_name: "Blackfire Boardgame Sleeves - Square (72x73mm)"
search_price: "2.95"
store_price: "2,95"

I want to get the price (store_price) from this JSON object and show this on my HTML site. Used the find and findIndex function but I constantly get a -1 returned.

The code I am using (based on this answer: Find object by id in an array of JavaScript objects):

    var product = "Blackfire Boardgame Sleeves - Square (72x73mm)";
    var price =  data.findIndex(x => x.products.product.product_name === product)

Making dropdown lists run function

I have adapted some code from the W3 hoverable dropdown tutorial and want to make it so that rather than following a link when clicked, it passes a value to a function. A rough snippet of the HTML code is below:

<div class="dropdown">
    <button class="dropbtn">Item</button>
    <div class="dropdown-content" (change)="selectChange($event)">
        <a value="egg">Egg</a>
        <a value="milk">Milk</a>
    </div>
</div>

I want to figure out how to get the value "egg" into the JavaScript function selectChange if the user clicks on that box, but currently, the boxes are not clickable and don’t do anything. I would like to avoid using a <select> tag if possible.

Here is the W3 link I got the structure of this code from:
https://www.w3schools.com/howto/howto_css_dropdown.asp

How can I have two IDs at once in an IF/ID statement?

I’m wanting to have two IDs in one if statement, like this:

if ($(this).attr("id") === "canopy-7-select" || "canopy-7-lc-select") {
    $(".canopy-7-image, .ao-c7").show();
} else { $('.canopy-7-image, .ao-c7').hide(); }

But I’m not sure how to make this work. Any ideas where I’m going wrong?

Thank you in advance.

How to remove an object item from an object where each value is an array of objects?

I have this object in state below and I would like to filter and return a new state with the selected object removed based on the id that is passed to an onClick.

Object in state:

const [data, setData] = useState({
   category1: [
      0: {
           category: "category1", id: 1, subcategory: "bob"
         },
      1: {
           category: "category1", id: 2, subcategory: "mike"
         },
   ],
   category2: [
      0: {
           category: "category2", id: 3, name: "swain"
         },
      1: {
           category: "category2", id: 4, name: "teemo"
         },
      2: {
           category: "category2", id: 5, name: "garen"
         }
   ]
})

Previously, I was able to remove a whole category itself with onClick with a passed in categoryName as the parameter with this code:

const filteredCategoryData = Object.fromEntries(
   Object.entries(data).filter(([key, value]) => key !== category)
);

setData(filteredCategoryData);

Now I want to extend on this logic and loop through the objects of each category and remove the subcategory based on id. I tried:

const filteredsubCategoryData = Object.fromEntries(
       Object.entries(data).filter(([key, value]) => {
       return value.filter(subCategory => subCategory.id !== id) 
    });
);

But this filteredsubCategoryData is returning the original intact state and I am confused on why.
Thank you for your help!

Is there a way to route to a HTML file instead of a JavaScript file with a react navbar?

Essentially I have created an html document for my website and I have a React NavBar javascript document for my navigation bar with buttons to each of the pages of my website (Home,etc..):

import React from "react";
import { Link } from "react-router-dom";
import styles from "./NavBar.module.css";

//TODO Web Template Studio: Add a new link in the NavBar for your page here.
// A skip link is included as an accessibility best practice. For more information visit https://www.w3.org/WAI/WCAG21/Techniques/general/G1.
const NavBar = () => {
  return (
    <React.Fragment>
      <div className={styles.skipLink}>
        <a href="#mainContent">Skip to Main Content</a>
      </div>
      <nav className="navbar navbar-expand-sm navbar-light border-bottom justify-content-between">
        <Link className="navbar-brand" to="/" role="heading" aria-level="1">
          SAMPLE
        </Link>
        <div className="navbar-nav">
          <Link className="nav-item nav-link active" to="/">
            Blank
          </Link>
          <Link className="nav-item nav-link active" to="Blank1">
            Blank1
          </Link>
          <Link className="nav-item nav-link active" to="Blank2">
            Blank2
          </Link>
        </div>
      </nav>
    </React.Fragment>
  );
}
export default NavBar; 

I also have an App.js document for routing for my pages:

import React from "react";
import { Switch, Route } from "react-router-dom";
import "./App.css";
import NavBar from "./components/NavBar/NavBar";
import Footer from "./components/Footer/Footer";

import Blank from "./components/Blank/Blank";

import Blank1 from "./components/Blank1/Blank1";

import Blank2 from "./components/Blank2/Blank2";

//TODO Web Template Studio: Add routes for your new pages here.
const App = () => {
    return (
      <React.Fragment>
        <NavBar />
        <Switch>
          <Route exact path = "/" component = { Blank } />
          <Route path = "/Blank1" component = { Blank1 } />
          <Route path = "/Blank2" component = { Blank2 } />
        </Switch>
        <Footer />
      </React.Fragment>
    );
}

export default App;

And this is what my Blank.js document looks like:

import React from "react";

const Blank = () => {
  return <main id="mainContent">
    <div className="container">
      <div className="row justify-content-center mt-5 p-0">
        <h3>Blank</h3>
      </div>
    </div>
  </main>
}
export default Blank;

Is there any way I could route to an HTML document instead of .js, because I already have my page in HTML and it doesn’t work if I just add it to Blank.js with the appropriate tags.

Thank you so much!

Import Capacitor Community plugin into a vanilla js script

I have a basic app written in pure javascript (index.html, script.js) which i put into a CapacitorJs project to let me create ios/android apps. which work perfectly fine even on my phone.

But now i’m trying to use a capacitor community plugin (@capacitor-community/contacts) but i need to import it in my script.js like this

import { Contact, Contacts, NewContact } from '@capacitor-community/contacts';

Since i’m not using typescript it obviously throw an error.

How can i manage to make it work ?

  • I have tried to import it through a <script type="module"> on my index.html and assign it to the js global window variable to access it in my script.js but it doesn’t work.

  • I have also tried to convert my scripts.js to a typescript and compile it with the following config:

{
  "target":"es5",
  "module":"es2015",
  "moduleResolution:"node"
}

And to make it work, had to change the import string to:
import { Contact, Contacts, NewContact } from '../../nodes_modules/@capacitor-community/contacts';

But then i get an error on the console saying TypeError: 'text/html' is not a valid Javascript MIME type

  • I ve tried also with the following config
  "target":"commonjs",

But got error with “define” not being recognized in the browser.

  • I am also aware of “bundledWebRuntime”: true, that basically compile capacitor core files into a .js that you import in your index.html. But it doesn’t include community packages so it’s not a solution.

Sorting by two properties (JavaScript) [duplicate]

I have an array of objects. I am trying to sort by totalPrice property but if totalPrice is the same, I then want to sort by dailyPrice. How I can achieve this to sort by both properties? I thought by adding || statement that it would solve this. Thanks!

Code Sample

const vehicles = [{ totalPrice: 80, dailyPrice: 62}, {totalPrice: 80, dailyPrice: 60}]
vehicles.sort((vehicle) => vehicle.totalPrice || vehicle.dailyPrice)
console.log('sorted:', vehicles)

Telegram bot for poll. Keyboard (Node.js)

I am writing a telegram-bot-questionnaire. There was a problem with the keyboard, namely with one button. And the text of the button after clicking on it, for some reason I send to the chat. How to make a bot send a message immediately after pressing a button? Please tell me how to solve this problem?

if (text === '/start') {
await bot.sendMessage(msg.chat.id, 'message 1')
await bot.sendMessage(msg.chat.id, 'message 2', {
  reply_markup: {
    keyboard: [
      [{
        text: 'event 1'
      }]
    ]
  }
})

if ('event 1') {
  await bot.sendMessage(msg.chat.id, "message 3")
  await bot.sendMessage(msg.chat.id, "message 4", {
    reply_markup: {
      keyboard: [
        [{
          text: 'event 2'
        }]
      ]
    }
  })
}

}

The script from “url” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type

hi guys i got this project form a costumer. and when ever try to run it it doesn’t show any content on the page and there is no errors in the terminal ,but it shows this whenever i inspect it =>

this the error:the image

this is the github repo :
https://github.com/HashLips/hashlips_nft_minting_dapp

i just added a smart contracts .

i have no idea where the bug came from ,it doesn’t display any content on the page.
thank you in advance 🙂

Sequelize Not Creating a Through Table

I am trying to associate a User model and an Age model with a many to many relationship. The user and age model are being created however the through table isn’t. Here is my code:

const { Sequelize, Op, QueryTypes } = require('sequelize')
const db = new Sequelize('postgres://localhost:5432/sqlstuff', {
  logging: false
})

const Age = db.define('Age', { age: Sequelize.INTEGER }, { timestamps: false })

const User = db.define('User', {
  firstName: Sequelize.STRING,
  lastName: Sequelize.STRING,
}, { timestamps: false })

async function create() {
  try {
    //Both Users and Ages Table are created. Both tables are properly populated
    const people = await User.bulkCreate([
      { firstName: 'Tyler', lastName: 'Kumar'},
      { firstName: 'Sabi', lastName: 'Kumar'}
    ], { validate: true }, { fields: ['firstName', 'lastName']})
    const myAge = await Age.create({ age: 22 })
    //Line 21 and 22 do not create a through table, unsure why
    User.belongsToMany(Age, { through: 'UserAges' })
    Age.belongsToMany(User, { through: 'UserAges' })
    //Line 23 creates the error 'relation "UserAges" does not exist'
    await people[1].addAge(myAge)
  } catch (error) {
    console.error(error)
  }
}

async function connect() {
  try {
    await db.sync({ force: true })
    await create()
    await db.close()
  } catch (error) {
    console.error(error)
  }
}

connect()

When button on a specific row clicked, how to gather data from that row and pass to server

I am using dynamically generated rows with my application that gather which stocks a user currently has in their portfolio. The HTML for the portfolio page is as follows:

{% block main %}
    <form action="/" method="get">
        <table class="table table-striped center">
            <thead>
                <tr>
                    <th class="text-start">Symbol</th>
                    <th class="text-start">Name</th>
                    <th class="text-end">Shares</th>
                    <th class="text-end">Price</th>
                    <th class="text-end">TOTAL</th>
                    <th class="text-middle">Buy/Sell</th>
                </tr>
            </thead>
            <tbody>
                {% for stock in stocks %}
                <tr id="selected">
                    <td class="text-start" id="symbol">{{ stock["symbol"] }}</td>
                    <td class="text-start">{{ stock["name"] }}</td>
                    <td class="text-end">{{ stock["shares"] }}</td>
                    <td class="text-end">{{ stock["price"] | usd }}</td>
                    <td class="text-end">{{ ((stock["price"]) * (stock["shares"])) | usd }}</td>
                    <td class="text-middle">
                        <input type="number" min="1" name="shares" placeholder="shares" style="width:80px">
                        <button type="submit" name="action" value="sell" class="btn btn-primary button">Sell</button>
                        <button type="submit" name="action" value="sell" class="btn btn-primary button">Buy</button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="4" class="text-end"><b>Cash</b></td>
                    <td class="text-end">{{ cash[0]["cash"] | usd }}</td>
                </tr>
                <tr>
                    <td colspan="4" class="text-end"><b>TOTAL</b></td>
                    <td class="text-end">{{ total | usd }}</td>
                </tr>
            </tfoot>
        </table>
    </form>

This turns out to look as follows:
enter image description here

My question is about the sell and buy buttons and the input field associated with each row. Using javaScript, how can I decipher which row the button was clicked on and then gather that rows data and pass to the server side to then check and update that users database of stocks? I have fiddled and looked around and got this but have not been able to connect the dots…

    <script>
        document.querySelector("form").addEventListener("submit", function(event) {
            let row = event.target.parentNode.parentNode.id;
            let data = document.getElementbyId(row).querySelector("#symbol");
            console.log(data);
        });
    </script>
{% endblock %}

How to override VSCode Intellisense inference with JSDoc comment

VSCode’s Intellisense ignores my JSDoc comment and infers what the definition should be when using a function that returns a function (in this case, it’s RamdaJS.reduce)

/**
 * @param { Array<number> } arrayOfNumbers
 * @return { number } sum - the sum of the arrayOfNumbers
 */
const getSumOfArrayElements = reduce (add, 0)

VSCode output:

const getSumOfArrayElements: (list: readonly any[]) => number
@param arrayOfNumbers

@return — sum - the sum of the arrayOfNumbers

Intellisense is defining getSumOfArrayElements as the definition for the return value of reduce (add, 0) (reduce with 2 arguments supplied)

Is there a way to have JSDoc comments have top priority in VSCode?

Thanks!