Split an array into an array with different objects

I was working on a plain array but I want the structure of the array to be in a sub-array form with multiple entries inside it. I tried forEach but when I push the element the whole array is pushed inside the sub-array.
The array that I have

data = ["1640662522","1640663240","1640663967","1640664659","1640665388","1640666124","1640666829","1640667505","1640668278","1640668984"];

but I want the structure of my new array to be

    {
"sizeData":[
 {
           "timestamp":1640662522,
           "size":12345,
           "fees":12589,
           "cost":168
},
 {
           "timestamp":1640663240,
           "size":12345,
           "fees":12589,
           "cost":168},
 {
           "timestamp":1640663967,
           "size":12345,
           "fees":12589,
           "cost":168
}, {
           "timestamp":1640664659,
           "size":12345,
           "fees":12589,
           "cost":168
}
]

Could anyone help me on this.
I am working on js for this

How to use framer motion animation with swiper.js (React)?

So the animations are only occurring during the initial page reload. I want the animations to execute every time I scroll down to another page. How do I use react-router with swiper and framer or is there any other way to do it.
This is my app.js

import React, { useRef, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import Home from "./Home";
import Works from "./Works";
import "./styles.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import Navbar from "./Navbar";

import SwiperCore, {
  Mousewheel,
  Keyboard,
  Pagination,
  Navigation,
} from "swiper";

// install Swiper modules
SwiperCore.use([Mousewheel, Pagination]);

export default function App() {
  let i = 0;
  return (
    <>
      <Swiper
        onScroll={() => {
          //console.log("Scrolled");
          localStorage.setItem("scrolled", (i = i + 1));
          console.log(localStorage.getItem("scrolled"));
        }}
        direction={"vertical"}
        slidesPerView={1}
        spaceBetween={30}
        mousewheel={true}
        className="mySwiper"
      >
        <SwiperSlide>
          <Home />
        </SwiperSlide>
        <SwiperSlide>
          <Works />
        </SwiperSlide>
        <SwiperSlide>Slide 3</SwiperSlide>
        <SwiperSlide>Slide 4</SwiperSlide>
        <SwiperSlide>Slide 5</SwiperSlide>
        <SwiperSlide>Slide 6</SwiperSlide>
        <SwiperSlide>Slide 7</SwiperSlide>
        <SwiperSlide>Slide 8</SwiperSlide>
        <SwiperSlide>Slide 9</SwiperSlide>
      </Swiper>
    </>
  );
}

This is one of my components Home.js

import React, { useEffect, useState } from "react";
import "./App.css";
import ClimbingBoxLoader from "react-spinners/ClimbingBoxLoader";
import "./mainpage.css";
import cloud1 from "./images/cloud1.svg";
import cloud02 from "./images/cloud02.svg";
import cloud2 from "./images/cloud2.svg";
import moon from "./images/moon.svg";
import cloud3 from "./images/cloud3.svg";
import cloud01 from "./images/cloud01.svg";
import { useNavigate } from "react-router-dom";
import {
  MouseParallaxChild,
  MouseParallaxContainer,
} from "react-parallax-mouse";
import Navbar from "./Navbar";
import { motion, useViewportScroll, useTransform } from "framer-motion";

function Home() {
  const fadeLeft = {
    hidden: { opacity: 0, x: -100 },
    visible: { opacity: 1, x: 0 },
  };

  const fadeRight = {
    hidden: { opacity: 0, x: 100 },
    visible: { opacity: 1, x: 0 },
  };

  const [loading, setloading] = useState(false);
  useEffect(() => {
    setloading(true);
    setTimeout(() => {
      setloading(false);
    }, 1000);
  }, []);

  return (
    <MouseParallaxContainer className="App">
      {loading ? (
        <ClimbingBoxLoader size={20} color={"#F37A24"} loading={loading} />
      ) : (
        <MouseParallaxContainer
          className="main-page"
          containerStyles={{
            width: "100%",
            overflow: "none",
          }}
        >
          <Navbar />
          <motion.h1
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.5 }}
            className="heading"
          >
            SASWATA
          </motion.h1>
          <motion.h1
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.5 }}
            className="heading2"
          >
            GHOSH
          </motion.h1>
          <motion.span
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.7 }}
            className="bar1"
          ></motion.span>
          <motion.span
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 0.85 }}
            className="bar2"
          ></motion.span>
          <motion.p
            variants={fadeLeft}
            initial="hidden"
            animate="visible"
            transition={{ duration: 1 }}
            className="para"
          >
            web developer
          </motion.p>
          <p className="scrolldown">SCROLL DOWN</p>
          <span className="verticaline"></span>
          <MouseParallaxContainer
            className="moon"
            containerStyles={{
              width: "100%",
              overflow: "none",
            }}
          >
            <MouseParallaxChild
              className="moon_text"
              factorX={0.01}
              factorY={0.01}
            >
              <motion.p
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
              >
                PORTFOLIO
              </motion.p>
            </MouseParallaxChild>
            <MouseParallaxChild
              className="moon_img"
              factorX={0.03}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.7 }}
                src={moon}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud01"
              factorX={0.04}
              factorY={0.06}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.8 }}
                src={cloud01}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud02"
              factorX={0.03}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
                src={cloud02}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud_front1"
              factorX={0.04}
              factorY={0.07}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.7 }}
                src={cloud1}
                alt="cloud1"
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud3"
              factorX={0.03}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
                src={cloud3}
                alt=""
              />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud2"
              factorX={0.06}
              factorY={0.05}
            >
              <motion.img
                variants={fadeRight}
                initial="hidden"
                animate="visible"
                transition={{ duration: 0.5 }}
                src={cloud2}
                alt="cloud2"
              />
            </MouseParallaxChild>
          </MouseParallaxContainer>
          <div className="nav-left">
            <span style={{ width: "40px" }} className="span1"></span>
            <span style={{ width: "25px" }} className="span2"></span>
            <span style={{ width: "25px" }} className="span3"></span>
            <span style={{ width: "25px" }} className="span4"></span>
          </div>
        </MouseParallaxContainer>
      )}
    </MouseParallaxContainer>
  );
}

export default Home;

After going through several videos and documentation I was not able to figure it out.

sort in descending if obj of array is number.else in ascending order. in angular javascript

i have an array of objects. if each obj consists of year followed by title. then year should be in descending order and title should be in ascending order.

ex:
i have an array like
[2018 Apple,2017 Car , 2022 Ball ,2021 Dog,2021 Box,2018 Bat];

my sorting requirement would be like

[2022 Ball, 2021 Box , 2021 Dog , 2018 Apple ,2018 Bat,2017Car]

if you observe for 2021 and 2018 their titles are appearing in ascending and all years are appearing in descending.

in javascript /angular!

changing next.js pages after building

My project has 3 folders: server(node.js), client(next.js with custom server) and uploads(the images of products).
I have uploaded it in a Ubuntu 20.04 server and build next.js project. it works.
I have recently changed some pages of next.js and uploaded to client folder by “sudo git pull”.
Now I would like to run “npm run build” to build next.js again, but it gives Error:

warn - No ESLint configuration detected. Run next lint to begin setup

Build error occurred
Error: > Build directory is not writeable. https://nextjs.org/docs/messages/build-dir-not-writeable
at /home/skadmin/client/node_modules/next/dist/build/index.js:275:19
at async Span.traceAsyncFn (/home/skadmin/client/node_modules/next/dist/telemetry/trace/trace.js:60:20)
at async Object.build [as default] (/home/skadmin/client/node_modules/next/dist/build/index.js:77:25)
info - Creating an optimized production build

==========My Custom server is:
”’

const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
.prepare()
.then(() => {
const server = express()
// apply proxy in dev mode
if (dev) {
server.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
)
}

server.all('*', (req, res) => {
  return handle(req, res)
})

server.listen(3000, (err) => {
  if (err) throw err
  console.log('> Ready on http://localhost:8000')
})
})
.catch((err) => {
console.log('Error', err)
})

”’
=======================package.json is=>:
”’

{
"name": "client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@ant-design/icons": "^4.5.0",
"@glidejs/glide": "^3.4.1",
"@material-ui/core": "^4.11.4",
"@material-ui/icons": "^4.11.2",
"@persian-tools/persian-tools": "^3.0.1",
"antd": "^4.13.1",
"axios": "^0.21.4",
"express": "^4.17.1",
"http-proxy-middleware": "^2.0.0",
"lodash": "^4.17.21",
"moment-jalaali": "^0.9.2",
"multer": "^1.4.4",
"next": "^11.1.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-image-file-resizer": "^0.4.7",
"react-markdown": "^6.0.2",
"react-scroll": "^1.8.2",
"react-toastify": "^7.0.4",
"reactstrap": "^8.9.0",
"swiper": "^7.4.1"
}
}

”’

Please help me, what should I do?

curl SyntaxError: Unexpected token ‘ in JSON at position 0

I’m trying to build an api, the get all method works, but I’m really struggling to test my post method. I’m using the command curl http://localhost:5000/api/properties -X POST -H "Content-Type: application/json" -d '{"externalId": "hola"}' and I’m getting the following error:

SyntaxError: Unexpected token ' in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesbody-parserlibtypesjson.js:158:10)
    at parse (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesbody-parserlibtypesjson.js:83:15)
    at C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesbody-parserlibread.js:121:18
    at invokeCallback (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesraw-bodyindex.js:224:16)
    at done (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesraw-bodyindex.js:213:7)
    at IncomingMessage.onEnd (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesraw-bodyindex.js:273:7)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

I’ve tried changing the curl command but nothing changes, also tried to do it using postman but also not working.

My code:

index.js:

const express = require("express")
const mongoose = require("mongoose")
const routes = require("./routes/routes")

// Connect to MongoDB database
mongoose
    .connect("mongodb://localhost:27017/propertyDB", { useNewUrlParser: true })
    .then(() => {
        const app = express()

        app.use(express.json())
        app.use("/api", routes)
        
        app.listen(5000, () => {
            console.log("Server has started!")
        })
    })

routes.js:

const express = require("express")
const Property = require("../models/Property") // new
const router = express.Router()

// Get all posts
router.get("/properties", async (req, res) => {
    const properties = await Property.find()
    res.send(properties)
})

router.post("/properties", async (req, res) => {
    console.log(req.body) //not printing

    const property = new Property({
        externalId: req.body.externalId,
    })
    await property.save()
    res.send(property)
})

router.get("/properties/:id", async (req, res) => {
    const property = await Property.findOne({ _id: req.params.id })
    res.send(property)
})

module.exports = router

Does anyone know what am I doing wrong?

Thank you!

string containing white space or not in react

if string contain white space alert should be unsuccessful and if string contain no white space alert should be successful
import React from “react”;
export default function DropDown() {

  let i=document.getElementById("input")?.value;
const submit=()=>{
  var whiteSpaceExp = /^s+$/g;
  if (whiteSpaceExp.test(i))
  {
  alert('unsuccess');
  }
  else
  {
    alert('success');
  }
  }
return (
    <>
      <form>
        <input type="text" id="input"  autoComplete="off" />
        <button onClick={submit}> click  </button>
      </form>
    </>
  );
}

Best way to receive condtional statement with REST API

I’m creating dynamic table. This table contains few columns like: topic, state, theme, priority. On every row, I can make certain actions, but those are also dynamic. So let’s say I’m receiving 10 different actions and one action, like delete, should only be visible when priority equals 10. Now this condition (priority === 10) should be in response. What would be the best way to send and consume that?

How do I mock fetch in Jest

I want to mock the fetch in the Message function

const Message = () => { 
                const url = process.env.REACT_APP_BACKEND_URL  +"/helloworld" 
                console.log(url)
                const response = fetch(url)
                console.log(response)
                return response.text        
     }
export default Message

I should be mocked i the Jest test

import App from './App' 
import {render,screen} from '@testing-library/react'
global.fetch = jest.fn(() =>  Promise.resolve({ text: () => Promise.resolve("Hello World")}))


it('should display hello world', async () => {
     render(<App />);
     const linkElement = screen.getByText('Hello World');
     expect(linkElement).toBeInTheDocument();
 })

Coode that should be tested look like this

import React from ‘react’
import Message from ‘./Message’

function App () {
    return <Message />
 }

export default  App ;

When I run the test I get following message

FAIL  src/App.test.jsx
  ✕ should display hello world (147 ms)

  ● should display hello world

    TypeError: Cannot read property 'text' of undefined

       6 |                 const response = fetch(url)
       7 |                 console.log(response)
    >  8 |                 return response.text        
         |                                 ^
       9 |      }
      10 | export default Message

      at Message (src/Message.jsx:8:33)

How do I mock the fetch?

Setting selenium request header

I am trying to set the request header in selenium. For one or another reason, I am not able to find how to set such a header.

If I read correctly, this is not possible and I would need an extension in Chrome to set the request header: setting request headers in selenium

Is this answer still up to date? And are there other ways to implement a header in a get request using selenium?

I am using node js and selenium to build a web scraper.

Thanks in advance.

How to detect system font using JavaScript?

I am working on a CDKEditor5 for which I have to configure one functionality. when i edit or try to write a mail on it then they automatically take the default system language (which clients currently use in their system). so have you guys any idea about this how to done?. using javascript & angular.
If any library is available then help me. or any customize javascript for it?

How can I reorder divs within this container that I am looping over?

jQuery(document).ready(function($) {

  if ($('.category-sidebar')) {

    var $filterWrap = $('#filter-wrapper .filter-container');

    $('#narrow-by-list').empty();

    $filterWrap.each(function (index) {
      var $currFilter = $(this);
      var $divParent = $currFilter.closest('.filter-container');
      var divHeader = $currFilter.find('.toggle-category-header').text().trim();

      /*if (divHeader === 'Color') {
        $divParent.appendTo('#narrow-by-list');
      } else if (divHeader === 'Clothes Size') {
        $divParent.appendTo('#narrow-by-list');
      } else if (divHeader === 'Price') {
        $divParent.appendTo('#narrow-by-list');
      } else if (divHeader === 'Product Type') {
      } else if (divHeader === 'Shop By Figure') {
      }*/

      switch (divHeader)
      {
        case 'Color':   
        case 'Clothes Size':         
        case 'Price':
          $divParent.appendTo('#narrow-by-list');
          break;
        case 'Product Type': 
        case 'Shop By Figure':          
          $divParent.appendTo('#narrow-by-list :last-child');
          break;
      } 
    });
  }

});
  • $filterWrap is the container that hold five side navbar items that are all divs

  • #narrow-by-list is tag that holds #filterwrapper which holds all 5 divs

  • I want to be able to reorder the divs and place them inside the same container so right now they are:

  • Color

  • Shop By Figure

  • Product Type

  • Clothes Size

  • Price

I want the list of divs to be reordered to:

  • Colour
  • Size
  • Price
  • Product Type
  • Shop By Figure

The code above sorts the first three but can’t get the last two sorted. Can you guys help?