Javascript, Duplicate an object and use different values [duplicate]

is there a way I can duplicate a Object in javascript but then have different values in the duplicate;

For example if the original Object is as follows:

    a           = [];
    a[0]        = {};
    a[0].milk   = "Malted";
    a[1]        = {};
    a[1].milk   = "Goats";

I then want to copy the Object

    b = a;
    b[0].milk = "Semi";

If I use clone() or assign the previous ‘a’ Object is also altered so if I wrote

document.write(a[0].milk+" * "+b[0].milk);

The output is:

Semi * Semi where I am expecting Malted, Semi

Thanks in advance.

Cannot read properties of undefined (reading ‘getState’)

TypeError: Cannot read properties of undefined (reading ‘getState’) at /home/ubuntu/online-coding-judge/submissions/1466948/unit-6/sprint-4/day-3/assignments/ReactTheme/node_modules/react-redux/lib/components/Provider.js:36:57 at mountMemo (/home/ubuntu/online-coding-judge/submissions/1466948/unit-6/sprint-4/day-3/assignments/ReactTheme/node_modules/react-dom/cjs/react-dom.development.js:17225:19) at Object.useMemo (/home/ubuntu/online-coding-judge/submissions/1466948/unit-6/sprint-4/day-3/assignments/ReactTheme/node_modules/react-dom/cjs/react-dom.development.js:17670:16) at useMemo (/home/ubuntu/online-coding-judge/submissions/1466948/unit-6/sprint-4/day-3/assignments/ReactTheme/node_modules/react/cjs/react.development.js:1650:21) at Provider (/home/ubuntu/online-coding-judge/submissions/1466948/unit-6/sprint-4/day-3/assig

i got this error and not a pass single test case can any one please help me to find out whats wrong in code

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import store from "./Redux/store";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
        <Provider store={store}>

                <App />
        </Provider>


);

reportWebVitals();


import "./App.css";
import Counter from "./Components/Counter";
import Theme from "./Components/Theme";
function App() {
  return (
    <div className="App">
      <Theme />
      <Counter />
    </div>

  );
}

export default App;
import { legacy_createStore as createStore, combineReducers } from "redux";
import { counterReducer } from "./counterReducer";
import { themeReducer } from "./themeReducer";


const rootReducer = combineReducers({
        counterReducer,
        themeReducer,
});
const store = createStore(rootReducer);

export default store;
//Complete the reducer function logic inside the curly braces {}
// the theme initstate shouldbe light
import { CHANGE_THEME } from "./actionTypes";
const themeReducer = (state = "light", action) => {
        switch (action.type) {
                case CHANGE_THEME:
                        return action.payload;
                default:
                        return state;
        }
};

export { themeReducer };
//Complete the reducer function logic inside the curly braces {}
// the counter initstate shouldbe 10
import { ADD, REDUCE } from "./actionTypes";


const counterReducer = (state = 10, action) => {
        switch (action.type) {
                case ADD:
                        return state + action.payload;
                case REDUCE:
                        return state - action.payload;
                default:
                        return state;
        }
};

export { counterReducer };
//DO NOT change the function names

import { ADD, REDUCE, CHANGE_THEME } from "./actionTypes";

const handleAdd = () => {
        return { type: ADD, payload: 1 };
};

const handleReduce = () => {
        return { type: REDUCE, payload: 1 };
};
const handleTheme = (theme) => {
        return { type: CHANGE_THEME, payload: theme };
};

export { handleAdd, handleReduce, handleTheme };
import React from "react";
import { useSelector } from "react-redux";
import CounterValue from "./CounterValue";
import CounterButtons from "./CounterButtons";
import './counter.css'

const Counter = () => {
  const theme = useSelector((state) => state.themeReducer);
  return (
    // the following div classname should be chnaged accrding to the theme
    <div className={`counter ${theme === "light" ? "light-theme" : "dark-theme"}`} data-testid="counter">
      <h1>Counter</h1>
      <CounterValue />
      <CounterButtons />
      {/* Import CounterValue component here and DO NOT PASS anything through props, for this component */}

      {/* Import CounterButtons component here and DO NOT PASS anything through props, for this component */}
    </div>
  );
};

export default Counter;
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { handleTheme } from '../Redux/action.js'
import './Theme.css'
const Theme = () => {
        const dispatch = useDispatch();
        const theme = useSelector((state) => state.themeReducer);

        const handleThemeChange = (newTheme) => {
                dispatch(handleTheme(newTheme));
        };

        return (
                <div >
                        <button
                                data-testid="switchToLightButton"
                                disabled={theme === "light"}
                                onClick={() => handleThemeChange("light")}
                        >
                                Switch to Light
                        </button>
                        <button
                                data-testid="switchToDarkButton"
                                disabled={theme === "dark"}
                                onClick={() => handleThemeChange("dark")}
                        >
                                Switch to Dark
                        </button>
                </div>
        );
};

export default Theme;
import React from "react";
import { useSelector } from "react-redux";

const CounterValue = () => {
  const counter = useSelector((state) => state.counterReducer);

  return <div data-testid="counterValue">{counter}</div>;
};

export default CounterValue;

I am getting error please help me

How to render components after navigate in React?

I’m writing a React app using react-router-dom for navigation. When using navigate(), I can see in devtools that the ‘root’ root component is being rendered. However, in the code snippet below, the console does not work, what is the reason for this?

function App() {
  useEffect(() => {
    console.log(123);
  });

  return (
    <Provider store={store}>
      <UserProvider>
        <RouterProvider router={router}/>
      </UserProvider>
    </Provider>
  );
}

Javascript: change the field names of the object in the array

I need to replace the field names of the object in the array with the value of the object in it.

the state i want it to be:

enter image description here

current state:

enter image description here

code:

let data1 = tableRows.map(o =>
                    Object.entries(o).map(
                        ([name, value]) => ({ name, value })
                    )
                    .map(e =>
                        {
                            if (tbl.fields.some(u => u == e.name)) { return e }
                        }
                    )
                )
                .map(x => x.filter(a => a != undefined));

currently there is array inside array and ‘name’ is allocated as ‘value’. I want to make the data in the ‘name’ part the field name, and the data in the ‘value’ part as values. So like in the first photo.

Removing a product from the cart

when I try to remove a product from the cart, all products get removed instead of one, here’s the code:

  const removeItem = (id: number) => {
    const updatedCartItems = cartItems.filter((item) => item.id !== id);
    setCartItems(updatedCartItems);
    localStorage.setItem("cart", JSON.stringify(updatedCartItems));
  };

It’s pretty much self explanatory, I explained above.

Here’s the whole code if it helps:

shop.cart.tsx:

import { useEffect, useState } from "react";
import { Product } from "./shop.electronics";
import "app/styles/shop.cart.css";

export default function Cart() {
  const [cartItems, setCartItems] = useState<Product[]>([]);

  useEffect(() => {
    const existingCart = JSON.parse(localStorage.getItem("cart") || "[]");
    setCartItems(existingCart);
  }, []);

  const clearCart = () => {
    setCartItems([]);
    localStorage.removeItem("cart");
  };
  const removeItem = (id: number) => {
    const updatedCartItems = cartItems.filter((item) => item.id !== id);
    setCartItems(updatedCartItems);
    localStorage.setItem("cart", JSON.stringify(updatedCartItems));
  };

  const getTotalPrice = () => {
    return cartItems.reduce((total, item) => total + item.price, 0);
  };

  return (
    <div className="cart">
      <h2>Shopping Cart</h2>
      {cartItems.length === 0 ? (
        <p>Your cart is empty.</p>
      ) : (
        <div>
          <ul>
            {cartItems.map((item) => (
              <li key={item.id}>
                <div className="cart-item">
                  <img src={item.image} alt={item.title} />
                  <div className="cart-item-details">
                    <h3>{item.title}</h3>
                    <p>Price: ${item.price}</p>
                    <button
                      className="button-remove"
                      onClick={() => removeItem(item.id)}
                    >
                      Remove
                    </button>
                  </div>
                </div>
              </li>
            ))}
          </ul>
          <p className="total-price">
            Total Price: ${getTotalPrice().toFixed(2)}
          </p>
          <button className="clear-button" onClick={clearCart}>
            Clear Cart
          </button>
        </div>
      )}
    </div>
  );
}

Find the difference between two dates in js?

I want to find the difference between two dates,

I have an array which contains objects that include a startDate and endDate.

I have been trying this.

 testData.forEach((item) => {
  const { endDate, startDate } =
    item;

  if (workflow_instances_timestamp && workflow_instances_modified_at) {
    let startDate_ = new Date(startDate );
    let endDate_ = new Date(endDate);

    const seconds =
      Math.abs(endDate_.getTime() - startDate_.getTime()) / 1000;

    console.log(startDate, "startDate");
    console.log(endDate, "endDate");
    console.log(seconds % 60, "seconds");
  }
});

the data contains this array

const items = [{endDate: "Fri Jun 30 2023 13:32:05 GMT+0200 (Central European Summer Time)", startDate: "Fri Jun 30 2023 15:31:51 GMT+0200 (Central European Summer Time)"}]

with this code I have provided the seconds are showing is 46 seconds.

Which its not correct.

Thanks a lot.

When highchart has pagination can we export multiple pages of highchart

I have chart which has pagination and data is coming from server side. I am export the one image of highchart using SVG it is working fine for one page but problem, is it possible to export multiple pages when chart has pagination.
I am using this script

$("body").on('click','.download-chart-btn', function() {
        html2canvas($(this).closest('.grid-stack-item-content').find('.dashboad_chart_render')[0]).then(function(canvas) {
                var imageUrl = canvas.toDataURL();
                var link = document.createElement('a');
                link.href = imageUrl;
                link.download = 'chart-image.png';
                link.click();
        });
    });

Please can you guide me.

enter image description here

Thanks

How do I make my Navbar button work when i click it

I tried to create a hamburger button that toggles my navbar on small screen but it doesnt seem to work, when i click the button nothing happens. How can i get the navbar to be displayed horizontally when the screen is big and show just the burger icon ( the three divs enclosed in the button element) when it is small but i also need the button to toggle navbar off and on ( hidden and block). where are my wrong?

"use client"
import React, { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';


const NavBar = () => {
  const [navState, setNavState] = useState(false);

  

  return (
    <div>
      <div className='navbar w-full h-fit text-gray-700 bg-white shadow-lg p-3 md:justify-around  md:flex-row flex-col md:items-center flex fixed z-10 opacity-90'>
        <div className='flex justify-between items-center align-middle'>
        <div>
          <Link href='/'>
            <Image
              src='/Images/BIK.svg'
              width={50}
              height={50}
              alt='Logo'
              className='hover:drop-shadow-xl rounded-full'
            />
          </Link>
        </div>
        <div className='md:hidden'>
          {/* Navbar hamburger */}
          <button className='bg-gray-200' onClick={()=>setNavState(!navState)}>
            <div className='w-[20] h-[3] bg-black hover:shadow-xl '></div>
            <div className='w-[20] h-[3] bg-black my-1 hover:shadow-xl'></div>
            <div className='w-[20] h-[3] bg-black hover:shadow-2xl'></div>
          </button>
        </div>
        </div>
        {navState &&
        (<ul className={'md:grid grid-cols-5 gap-1 md:gap-10 justify-between md:w-[600] items-center box-border pl-5'}>
          <li>
            <button className='listlink'>Home</button>
          </li>
          <li>
            <button className='listlink'><Link href="/about">About</Link></button>
          </li>
          <li>
            <button className='listlink'>Projects</button>
          </li>
          <li>
            <button className='listlink'>Skills</button>
          </li>
          <li>
            <button className='listlink'>Contact</button>
          </li>
        </ul>)}
        
      </div>
    </div>
  );
};

export default NavBar;

Overflow Scroll Behaviour Bug

The classical Overflow when a modal is open on the page the body is allowed to overScroll

I am aware there are ways to contain this:

1. Overscroll-behavior: contain;

Issue: With this is it does not works with portal elements

2. // On body overflow:hidden; position: relative

Issue: When multiple modals are opened everything is fine except when they are unmounted they remove the classes or styles from body that allows the scrolling for other modals. Just checked on bootstrap as well this issue exists there also.

I am also aware there are ways to do this by maintaining count for the number of modals opened. But is there any actual Only CSS based approach to solve this?

selecting the correct line when uploading data from excel (javascipt)

In an mvc project i have a ui screen written in .cshtml . I have some labels on this screen. I want to upload 4 of my labels Code, SalesPrice, ConsumerPrice, Discount labels to excel and write the data in excel to the labels. I have no problem installing Excel, I can print labels, but I can’t do this. The code field is a unique field, and I need to filter according to this field and write the values to the line where the required code value is. I have this code on my page. I need to make a placement according to this code. How can I do that?

<thead>
                            <tr>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.Item.Code)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.Item)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.IsVatIncluded)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.UseConsumerPrice)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.SalesPrice)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.ConsumerPrice)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.PriceDiscountRate)</th>
                                <th>@Html.VpLabelForDetail((PriceListItemInsertModel p) => p.DiscountedPrice)</th>
                            </tr>
                        </thead>
`
<script>
        $(function () {


            $('#btnFileSave').click(function (e) {
                var fileUpload = $("#priceListExcel_File").get(0);

                //var files = fileUpload.files;
                var file = fileUpload.files[0];
                // input canceled, return
                if (!file) return;

                var FR = new FileReader();
                FR.onload = function (e) {
                    var data = new Uint8Array(e.target.result);
                    var workbook = XLSX.read(data, { type: 'array' });
                    var firstSheet = workbook.Sheets[workbook.SheetNames[0]];

                    // header: 1 instructs xlsx to create an 'array of arrays'
                    var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
                    for (var i = 1; i < result.length; i++) {

                        var code = result[i][0]; // CODE değerini al
                        var salesPrice = result[i][1]; // SALES PRICE değerini al
                        var consumerPrice = result[i][2]; // CONSUMER PRICE değerini al
                        var discountRate = result[i][3]; // DISCOUNT RATE değerini al

                        var rowCode = code; // rowCode değişkenine CODE değerini ata

                        

                        var hidden= $("[value='" + result.code + "']")
                        var tr = $("[value='" + result.code + "']").closest("tr");
                        $(tr).find("[id$=SalesPrice]").val("salesPrice");
                        $(tr).find("[id$=ConsumerPrice]").val("consumerPrice");
                        $(tr).find("[id$=PriceDiscountRate]").val("discountRate");

                        if (rowCode === code) {
                            $("#Model_PriceListItems_" + i + "__SalesPrice").val(result[i][1]);
                            $("#Model_PriceListItems_" + i + "__ConsumerPrice").val(result[i][2]);
                            $("#Model_PriceListItems_" + i + "__PriceDiscountRate").val(result[i][3]);
                        }                      
                    }

                };
                FR.readAsArrayBuffer(file);
           
        });

    });

evaluateJavascript enabling button after input doesn’t make the button clickable

I’m trying to find a way to input the receipt number and click the ‘Check Status’ button on this website: https://egov.uscis.gov/

I can successfully enter a receipt number:

document.getElementById('receipt_number').value = '(receiptNumber)';

But the ‘Check Status’ button remains disabled.
I can enable the button with:

document.getElementsByName('initCaseSearch')[0].removeAttribute("disabled");

But even with it enabled I still can’t click it (errors as ‘undefined’). It looks like the webpage has some additional logic or validation that prevents automated form submission, so I tried:

document.forms[0].submit();

But it just reloads the page and doesn’t take the input receipt number.

Any ideas?

how to solve transport close on disconnect socket.io?

[Kindly take a look on code to understand what I

server side:--
 
socket.on('disconnect', function(userid) {
        users[userid]= socket.id;
        console.log(userid);
        io.emit("user_disconnect",userid);
            console.log('user disconnected');

  });

clint side :---

   var io = io("http://localhost:5500");
   io.emit("user_connected",sessionStorage.getItem('userid'));
   io.emit("disconnect",sessionStorage.getItem('userid'));
   io.on("user_connected",function(userid)
   {
    console.log(userid);
   })
   io.on("user_disconnect",function(userid)
   {
    console.log(userid);
   })

‘m trying to do ](https://i.stack.imgur.com/1QFjh.png)

I want to update database on disconnection , But it showing transport close instead on id .

reactjs – unable to set state variable even though console shows correct items?

I am trying to:

function Performance() {
    const [labelsLength, setLabelsLength] = useState(0);
  const [labels, setLabels] = useState([]);

   useEffect(() => {
    const fetchData = async () => {
      try {
        const navData = await getNaData();
        console.log("NA Data from labels:", naData); // Log the naData to the console
        setNavData(navData);
        // console.log("NaData:", NaData);
        // setLabels(naData.map((_, index) => `Label ${index + 1}`));
        // setLabels(naData.map((item, index) => `Label ${index + 1}`));
        setLabels(
          navData.map((item, index) => {
            console.log("Item:", item.date); // Print the item to the console
            return `Label ${item.date}`;
          })
        );

        setLabelsLength(naData.length);
        console.log("Labels:", labels);
        console.log("After labels", naData);
        console.log("After labels length", naData.length);
        console.log("Labels length:", labelsLength);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
    console.log("data", data);
  }, [xAxisInterval]);

For some reason the labels are not populated. The console.log statement for item prints out:

Item 1680552000000
Item 1680638400000
…so on.

Not sure what is going wrong here.

How to properly arrange labels of a circle?

I have a circle like the following:

enter image description here

As you might notice, labels from 0 to 9 have different proximity to the outer circle in comparison to other labels. My expectations are

  1. How can I have same distance of a label to the outer circle?
  2. How can I arrange labels so that they are in the middle of the line that comes from center, and not in the side of it?

You can find my code here: https://jsfiddle.net/vtydkrbe/

I tried to changethis part of my code to have symmetry of labels, but it did not work.

  let featureData = features.map((f, i) => {
    let angle = (Math.PI / 2) + (2 * Math.PI * i / features.length);
    let isLeftHalf = angle < Math.PI; // Check if the angle is in the left half of the circle

    let value = isLeftHalf ? 14.5 : 10.5; // Adjust the value for labels in left and right halves

    return {
      "name": f,
      "angle": angle,
      "line_coord": angleToCoordinate(angle, 180),
      "label_coord": angleToCoordinate(angle, value)
    };
  });

Selenium web driver does throws chrome errors node.js

My selenium web driver throws errors no matter what I do, I am running ubuntu docker, it has java installed and I installed google chrome as the last resort.

No matter what I do, I get errors. I tried running it with headless-chrome (v86) combined with chromedriver v 86, with selenium-webdriver node version 4.10.

If I use that, chrome just hangs on first webDriver.get(**) command.

WebDriverError: unknown error: Chrome failed to start: crashed.
  (unknown error: unable to discover open pages)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

Playing arround with configuration, no matter how I run it, it either throws

  • chrome crashed randomly. (Not responding)
  • chrome not reachable.
  • or version issues.

But to my understanding If technically Id use selenium 4.10 node. Chrome 114 and chromedriver 114, it should work. I am running headless, my arguments for running chrome are:

            '--headless=new',
            '--no-sandbox',
            '--disable-browser-side-navigation',
            '--disable-dev-s1hm-usage',
            '--single-process',

Tried playing around with these, to no victory it always drops errors with chrome.