How to populate a property value with javascript object to a javascript object?

say I have two arrays:

authors = [
  {
    name: 'Robert Martin',
    id: "afa51ab0-344d-11e9-a414-719c6709cf3e",
    born: 1952,
  },
  {
    name: 'Martin Fowler',
    id: "afa5b6f0-344d-11e9-a414-719c6709cf3e",
    born: 1963
  }
]
let books = [
  {
    title: 'Clean Code',
    published: 2008,
    author: 'Robert Martin',
    id: "afa5b6f4-344d-11e9-a414-719c6709cf3e",
    genres: ['refactoring']
  },
  {
    title: 'Agile software development',
    published: 2002,
    author: 'Robert Martin',
    id: "afa5b6f5-344d-11e9-a414-719c6709cf3e",
    genres: ['agile', 'patterns', 'design']
  },
  {
    title: 'Refactoring, edition 2',
    published: 2018,
    author: 'Martin Fowler',
    id: "afa5de00-344d-11e9-a414-719c6709cf3e",
    genres: ['refactoring']
  }
]

const Book = require(‘./controllers/book’)

const Author = require(‘./controllers/author’)

using mongoose object schema, book object’s author property wants to be populated with complete author object if book.author === author.name.

like this:

{
    title: 'Clean Code',
    published: 2008,
    author: {
               name: 'Robert Martin',
               id: "afa51ab0-344d-11e9-a414-719c6709cf3e",
               born: 1952,
               },
    id: "afa5b6f4-344d-11e9-a414-719c6709cf3e",
    genres: ['refactoring']
  },

I have tried this:

books.forEach(book => {
const bookAuthor = authors.find(author => book.author === author.name).name
Book.findOne({author: bookAuthor}).populate('author') }

no success, somehow js is hard to manipulate data structure on the fly than Python I feel. Could you help?

WebSocket Clear Values inside message nodejs

I am trying to display some data using websocket by fristCoinId and secondCoinId in nodejs i am using react as frontend but when i hit my request in the first time i get correct data but changing the coins on front its sends both selected coin data like this

firstCoinId, secondCoinId { firstCoinId: 15, secondCoinId: 36, userId: 160 }
firstCoinId, secondCoinId { firstCoinId: 49, secondCoinId: 36, userId: 160 }

buy i want to clear the first value and want only one set on values how can i do this here is my code

wsServer.on("request", function (request) {
var userUd = getUniqueId();
const connection = request.accept(null, request.origin);
client[userUd] = connection;
connection.on("message", async function (message) {
console.log("mesg", message);
var interval = 2000;
if (message.type === "utf8") {
  if (message.utf8Data) {
    console.log('scoker',message.utf8Data)
      var socketDataVar = setInterval(
        () => socketData(message.utf8Data),
        2000
      );
      const socketData = async (socket) => {
        var graphDataApi = await exchangeCtrl.graphData(socket);
        var topBarApi = await exchangeCtrl.topBar(socket);
        var balanceApi = await exchangeCtrl.userBalanceByPair(
          socket
        );
        var activeOrderListApi = await exchangeCtrl.activeOrderList(
          socket
        );
        var marketTradeApi = await exchangeCtrl.marketTradeApi(
          socket
        );
        var myActiveOrderListApi = await exchangeCtrl.myActiveOrderList(
          socket
        );
        var myCompletedOrderListApi =
          await exchangeCtrl.myCompletedOrderList(socket);
        var coinListApi = await exchangeCtrl.coinList(socket);
        var filalData = {
          graphDataApi,
          topBarApi,
          balanceApi,
          activeOrderListApi,
          marketTradeApi,
          myActiveOrderListApi,
          myCompletedOrderListApi,
          coinListApi,
        };
        for (key in client) {
          client[key].sendUTF(JSON.stringify(filalData));
        }
      };
    if (JSON.parse(message.utf8Data) == "disconnect") {
      clearInterval(socketDataVar);
    }
  }
}
});
});

Adding multiple scripts in Background.service_Worker in manifest file for chrome extension

I am currently using manifest V3 for developing a chrome extension. Earlier in v2 we have a ‘Scripts’ key in background section where we can pass multiple scripts file.

     "background": {
                     "scripts": ["background.js","hello.js","nice.js"]
                   },

But in v3 , scripts has been changed to service_worker and if I am using multiple scripts then it is showing error , So is there in any way to allow multiple scripts file in manifest v3 ?

   "background":{
                 "service_worker":["background.js","backgroundMSG.js"]
                }  // THIS IS NOT ALLOWED 

Unable to render two components from App.js

I am new to javascript and React. I am trying to render two components Layout and Home from App.js. When I tried rendering Layout component alone from App.js. Its working. But When I added Home component in App.js. Both are not working. Can anyone please help me out to resolve the issue. Below is my code

App.js

import './App.scss';
import { Routes, Route} from 'react-router-dom'
import React from 'react';
import Layout from './Components/Layout';
import Home from './Components/Home';

function App()
{
  return (
    <>
      <Routes>
      <Route path="/" element={<Layout />} />
      <Route index element={<Home />} />
         
      </Routes>
    </>
    )
}



export default App

Home.js


import LogoTitle from  '../../assets/images/logo-s.png'

const Home = () => {
    return (
        <div className="container home-page">
            <div className="text-zone">
                <hl>Hello World </h1>
            </div>
        </div>
    );
}


export default Home 

Get combo box selected value from JavaScript

I’m creating a web form using the bootstrap wizard.

Here I’m stuck within a few operations.

As a first step, I have added a drop-down menu and there in the selected event, I’m taking the selected value from the javascript. That’s working fine.

So in the next section, there is another combo box and the selection change event I also want to get the selected value of that combo box and the previously selected combo box value.

So I did this method but it does not return the selected value.

Can you help me with this?. Still, I’m not good with javascript

This is the first combo box.

 <div class="form-row center">
   <div class="form-holder"> @Html.DropDownListFor(model => model.Language, new SelectList(new[] { "English", "සිංහල", "தமிழ்" }),"Please Select the Language", new { @class = "form-control js-dropdown",Id ="DropLanguage" }) </div>
 </div>

This is the second Combo box

<div class="form-holder w-100">
  <div class="col-md-12"> @Html.DropDownList("ServiceTypeId", null,language == "Secondary" ? "For which service you came for?" : language == "Primary" ? "ඔබ පැමිණියේ කුමන සේවාව සඳහාද?" : language == "Third" ? "நீங்கள் எந்த சேவைக்காக வந்தீர்கள்" : "", htmlAttributes: new { @class = "form-control", Id = "ServiceType" }) <i class="zmdi zmdi-quote"></i> @Html.ValidationMessageFor(model => model.ServiceTypeId, "", new { @class = "text-danger" }) </div>
</div>

This is the javascript

< script type = "text/javascript" >
  $(document).ready(function () {
    $("#DropLanguage").on("change", function () {
      // This is the jQuery way of finding selected option's text
      var myVar = $(this).find("option:selected").text();

      // Post the value to your server. You should do some error handling here
      $.ajax({
        url: '/MainDetails/SetSession',
        type: 'POST',
        dataType: 'json',
        cache: false,
        async: false,
        data: {
          myVariable: myVar
        },
        success: function (data) {
          if (data.Success == true) {

            $("#mydiv").load(window.location.href + " #mydiv");
          }
        }
      });

    });

    $("#ServiceType").on("change", function () {

      var ServiceId = document.getElementById("ServiceType");
      var Language = document.getElementById("DropLanguage");

      alert(ServiceId);
      alert(Language);

    });
  });

<
/script>

Im not getting value on this section $("#ServiceType").on("change", function () {

Add event listener to chrome extension button

I am new to chrome extension development, and I understand that this question is simple but I couldn’t find it online. I was wondering how I could add a listener and hide or show a certain div on chrome extension button press. This is my current code in manifest.js for background where I am trying to connect chrome extension click (which is not working) to content.js.

"background": {
        "service_worker": "background.js"
    },

and this is my background.js file…

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.create({ 'url': "http://www.youtube.com/watch?v=oHg5SJYRHA0" });
    //above code used for testing but never gets executed for some reason when I try to click chrome extension button
});

Thank you in advance for your answers!!!

How can I fix ReactDOM.unmountComponentAtNode error in React?

The ReactDOM.unmountComponentAtNode(document.getElementById(“root”)); are unavailable in latest React.

It shows the errors below. How can I fix it?

“You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?”

“unmountComponentAtNode(): The node you’re attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.”

import {createRoot} from "react-dom/client";
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App tab={"home"} />);
root.unmount();
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
disappear = () => {  ReactDOM.unmountComponentAtNode(document.getElementById("root"));
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Script not running properly after Ajax call

I’m building my own portfolio website on WordPress and writing almost the whole code without plugins. The website features a home page with a dynamic ‘custom post types’ grid that I’ve implemented an Ajax filter according to the post taxonomy/category, reordering the posts according to the filter. This script runs on script.js:

(function ($) {

  $(document).ready(function () {
    $(document).on('click', '.js-filter-item', function (e) {
      e.preventDefault();
      $('.js-filter-item').removeClass('active');
      $('.js-filter').addClass('fade');
      $(this).addClass('active');
      setTimeout(function () {
        $('.js-filter').removeClass('fade');
      }, 500);
      var category = $(this).data('category');
      $.ajax({
        url: wpAjax.ajaxUrl,
        data: { action: 'filter', category: category },
        type: 'POST',
        success: function (result) {
          // $('.js-filter').html(result);
          setTimeout(function () {
            $('.js-filter').html(result);
          }, 200);
        },
        error: function (result) {
          console.warn(result);
        }
      })
    });
  });

I’ve also implemented a custom tooltip that follows the cursor and shows the post title on hover, as follows. This is running on the home page php file between tags:

var follower = $('.cursor-follower');
var posX = 0,
  posY = 0;
var mouseX = 0,
  mouseY = 0;
 
$('body').on('mousemove', function (e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  posX += (mouseX - posX) / 2;
            posY += (mouseY - posY) / 2;
  
  $('.cursor-follower').css(
    'top', (posY - 20) + 'px'
);
$('.cursor-follower').css(
    'left', (posX + 50) + 'px'
);
});

$('.animated-cursor').on('mouseenter', function () {
 console.log('olaaaaa');
  var dataTitle = $(this).attr('data-cursor-title');
  // var dataTags = $(this).attr('data-cursor-tags');
  follower.html(dataTitle + '<br>');
  follower.addClass('active');
});
$('.animated-cursor').on('mouseleave', function () {
  follower.removeClass('active');
});

And the query for the post grid (“animated-cursor” class and data-cursor-title are the relevant attributes):

if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();  ?>
    <div class="reveal item animated-cursor" data-cursor-title="<?php the_title(); ?>">
        <a href="<?php the_permalink(); ?>">
        <?php $pagina = get_page_by_title('<?php the_title(); ?>') ?>
          <img src="<?php the_field('imagem_capa', $pagina); ?>" alt="">
          <div class="post-info">
          <div>
            <h3><?php echo wp_strip_all_tags(get_the_term_list( $post->ID, 'portfolio_cat', '', ', ', '' )) ?></h3>
            <h2><?php the_title(); ?></h2>
</div>
          </div>
        </a>
      </div>
      <?php
        endwhile; 
      endif; 
      wp_reset_postdata(); 
       die();

Problem: the custom cursor tooltip doesn’t work on element hover after using the Ajax filter. Everything runs fine as planned after page load, but it doesn’t after anytime Ajax runs.

As far as I’m aware of (I’m a beginner on php, ajax, js), my script can only access the elements that are ready on page load. I’ve tried to make the script work after the Ajax call but I couldn’t find a workaround. Would anyone have any suggestion? I suppose it mustn’t be very complicated.

Thanks!

Sveltekit Error: `page` in `load` functions has been replaced by `url` and `params`

I am trying to display my date from GraphCMS in my blog application. I receive this error when I go to my single post link (http://localhost:3000/posts/union-types-and-sortable-relations)

“

page in load functions has been replaced by url and params
Error: page in load functions has been replaced by url and params

“

Here is my code

<script context='module'>
    export const load = async ({fetch, page: {params}}) => {
        const {slug} = params
        const res = await fetch(`/posts/${slug}.json`)
        if(res.ok) {
            const {post} = await res.json()
            return {
                props: {post},
            }
        }
    }
</script>

<script>
    export let post
</script>


<svelte:head>
    <title>Emrah's Blog | Welcome</title>
</svelte:head>

<pre>{JSON.stringify(post, null, 2)}</pre>

Can you please help. Thanks

React V6 having issues navigating from Class component

After making the changes required by react-router-dom 6, it seems like we no longer receive props from the dom, hence I am no longer able to navigate and pass params this way.

    this.props.history.push({
      pathname: "/search",
      state: sessionStorage.getItem("user"),
    });

I read that an alternative to that was to use useNavigate and it was possible to wrap a class component inside a function and export it as such:

// Wrap and export
export default function (props) {
  const navigation = useNavigate();
  return <login {...props} navigation={navigation} />;
}

This seems too hacky and did not work. anyone is using navigation with passing parameters in Dom v6? how is it done?

Thank you

How to make a shopping cart?

I’m totally a beginner to Javascript, and I need to make a virtual online grocery website for my uni project. I’m stuck with making a virtual cart by using Javascript.
I successfully display the specific product detail from my database when I click on the product title, but I have no idea how I can add the specific product and display the added products in my cart.php file.I know I should use SESSION, but as I could not find some samples that using the database to display the product details.

Below is my product.php file code:

“`

if ($conn->connect_error) {
die(“Connection error: ” . $conn->connect_error);
}

$product_name = “”;
$unit_price = “”;
$unit_quantity = “”;
$in_stock = “”;
$itemId = “”;
$showNoItem = “display: none”;
$showItem = “”;

if (isset($_GET[‘data’])) {
$itemId = $_GET[‘data’];
$sql = “SELECT product_id , product_name , unit_price, unit_quantity, in_stock FROM products where product_id=”.$itemId;
$result = $conn->query($sql);
if ($result->num_rows > 0) {

    $showNoItem = "display: none";
    $showItem = "";
    while($row = $result->fetch_assoc()) {
        $product_name = $row["product_name"];
        $unit_price =  $row["unit_price"];
        $unit_quantity =  $row["unit_quantity"];
        $in_stock =  $row["in_stock"];
        break;
    }
} else {

    $showNoItem = "";
    $showItem = "display: none";
}

} else {
$showNoItem = “”;
$showItem = “display: none”;
}

?>

“>Select items from categories on the left.
“>

()

    <div class="item-desp">
        <div class="in-stock-div">In Stock: <span class="item-in-stock"><?php echo $in_stock?> </span> </div>
        <div class="price-tag-div">Price: <span class="item-price-red">$<?php echo $unit_price ?></span></div>
        <p></p>
        

        <form action="cart.php" method="get" target="cart" class="order-row" onsubmit="return validate_quantity">
            <input type="number" class="item-quatity-input spin0" min="1" value="1" name="display" id="display" onkeyup="addCartButtonCtrl()" >
            <input type="hidden" name="productId" value="<?php echo $itemId?>">
            <input type="hidden" name="productInfo" value='<?php echo "$product_name($unit_quantity)"?>'>
            <input type="hidden" name="productPrice" value="<?php echo $unit_price ?>" >


            <div class="add-cart-div">
                <input id="cart-button" class="btn btn-primary" type="submit" value="Add to Cart" title="Add to cart." onclick="updateShoppingCart()">

            </div>
        </form>
    </div>

</div>

close();

?>

“`

I tried to use the function

$action = $_GET['action'];
            switch ($action) {
                case 'Add':
                    $product_id = $_GET['productId'];
                    $product_name = $_GET['productInfo'];
                    $unit_price = $_GET['ProductPrice'];

                    
                    if(!isset($_SESSION['cart'])) {
                        $_SESSION['cart']=array();
                    }

                    $index = getItemIndex($product_id);
                    if ($index < 0) {
                        $item_array=array('product_id' => $product_id,
                                          'product_name' => $product_name,
                                          'unit_price' => $unit_price,
}```
                    

                    

Error: Value for argument “value” is not a valid query constraint. “undefined” values are only ignored inside of objects

Whenever I am trying to execute one query as follows :

const user = {
        userHandle: req.body.userHandle
    };

    db.collection('todos')
        .where('userHandle', '==', user.userHandle)
        .get()
        .then((data) => {
            let todos = [];
            data.forEach((doc) => {
                todos.push({
                    todoId: doc.id,
                    body: doc.data().body,
                    isDone: doc.data().isDone,
                    userHandle: doc.data().userHandle,
                });
            });
            return res.json(todos);
        })
        .catch((err) => {
            console.error(err);
            res.status(500).json({ error: err });
        });
}

I get the below mentioned error in my google cloud console :

Error: Value for argument "value" is not a valid query constraint. "undefined" values are only ignored inside of objects.

at .Object.validateUserInput ( /workspace/node_modules/@google-cloud/firestore/build/src/serializer.js:274 )
at .validateQueryValue ( /workspace/node_modules/@google-cloud/firestore/build/src/reference.js:2230 )
at .CollectionReference.where ( /workspace/node_modules/@google-cloud/firestore/build/src/reference.js:1061 )
at exports.getAllTodoForOneUser ( /workspace/handlers/todos.js:29 )
at .Layer.handle ( /workspace/node_modules/express/lib/router/layer.js:95 )
at .next ( /workspace/node_modules/express/lib/router/route.js:137 )
at .Route.dispatch ( /workspace/node_modules/express/lib/router/route.js:112 )
at .Layer.handle ( /workspace/node_modules/express/lib/router/layer.js:95 )
at undefined. ( /workspace/node_modules/express/lib/router/index.js:281 )
at .Function.process_params ( /workspace/node_modules/express/lib/router/index.js:341 )

Also I am trying to query with the body using POSTMAN as follows :

{ "userHandle": "qmfUXw6YDwO9PQx1n13DjvPi2D23" }

The following is the screenshot of my firebase db.

enter image description here

Line combination algorithm

array=[[1,2],[13,14],[4,5],[80,30],[12,14],[10,90],[3,2],[6,9], [1,5] ,[4,5],[5,9],[4,3],[13,12]]

expected output=[[1,2],[13,14],[4,5],[80,30],[10,90],[3,2],[6,9] ,[4,5],[5,9],[4,3],[13,12]]

Think of the subarray,for example [1,2] will be a line connected from point 1 to point 2. Therefore, refering to above, since [1,2],[3,2],[4,3],[4,5],[4,3] means that it will connect to Point 1 to Point 5 because there is a line connected to Point 1 to 2,2 to 3,3 to 4, 4 to 5 and if the array contains its overall line combination that is Point 1 to Point 5, it will be filtered out from the array. This is done to filter out all short lines present with its node position in a long line. May I know the logic and the algorithm to solve this? Thank you for reading and have a nice day 🙂

I have tried the code below at https://codepen.io/Maximusssssu/pen/jOYXrNd?editors=0012:

The first part is to output all subarrays in ascending order for better view whereas for the second part,I have tried the include() method to check whether a node is present in the subarray and get its position.

array_ascending_arr=[];
for (let i=0;i<array.length;i++){
  let subarrayy=array[i].sort(function(a, b){return a-b}) ;
  array_ascending_arr.push(subarrayy);
}
console.log(array_ascending_arr)// output all subarrays in ascending order back into array
for (let k=1;k<5;k++){
for (let m=0;m<array.length;m++){
for (let i=1;i<2;i++){
if (array_ascending_arr[m].includes(k)==true){
  console.log(m)  }
}

}
    console.log(".......")
}

Permanently burn font to text

I have .ttf of the fonts, what i want to do is permanently burn font to the text, like coolfont.org

What i want is

Step 1: input text

Step 2: upload font

Output

Copy the text with font on clipboard

I’m stuck with this for quite a while any help would be appreciated, thanks