how to make complex data structure from array of objects

I have a result sheet with student names and subjects. There are more parts to a subject, like English first CQ, English first MCQ, English second CQ, English second MCQ,

The subject will have children, there will be 3 objects inside the children 1st paper, 2nd paper and AVG, The English first paper will be inside one child, the English second paper will be inside another child,

Also, each subject has a percentage and grade point which I want to show in a new object(AVG), inside the AVG object there will be a child which will have two objects percent and another one is GP. These three children will be inside an English object, as shown in the example. To find out if there are children in the subject, I have used Underscore (_)

result sheet field names

[
  {
    Field: "roll",
  },
  {
    Field: "name",
  },
  {
    Field: "english_1st_CQ",
  },
  {
    Field: "english_1st_MCQ",
  },
  {
    Field: "english_2nd_CQ",
  },
  {
    Field: "english_2nd_MCQ",
  },
  {
    Field: "english_percentage",
  },
  {
    Field: "english_GP",
  },
];

Output example

[
  0:{
    title: "Roll",
  },
  1:{
    title: "Name",
  },
  2:{
    title: "English",
    children: [
      0:{
        title: "1ST",
        children: [
          {
            title: "CQ",
            dataIndex: "CQ",
          },
          {
            title: "MCQ",
            dataIndex: "MCQ",
          },
        ],
      },
      1:{
        title: "2ND",
        children: [
          {
            title: "CQ",
            dataIndex: "CQ",
          },
          {
            title: "MCQ",
            dataIndex: "MCQ",
          },
        ],
      },
      2:{
        title: "AVG",
        children: [
          {
            title: "percentage",
            dataIndex: "percentage",
          },
          {
            title: "GP",
            dataIndex: "gp",
          },
        ],
      },
    ],
  },
]

Wrapper for console.debug(): How to color string while override function with Object.defineProperty()?

I built a class for logging, which gives the possibility to turn off the logging but to leave the calls in the code. (And with the right line and file.)

Based on that, I wanted a flashy color for todos, but I manage to color only the ‘[TODO]’, the rest of the text stays in the default color.

class Logger {

    // Don't forget console needs to be set to 'All levels' to display debug. ;)

    public OFF = 0;
    public LOG = 1;
    // ...
    public ALL = 9;
    
    private level = 1;
    
    public constructor() {
        /*this.init();*/ // killed for testing
    }
    
    // This is the original method.
    // Color is fine, but wrong line and file.
    public todo(message?: string, ...optionalParams: any[]) {
        const css = 'background: #FF0000; color: #0000FF';
        optionalParams.length != 0
            ? console.debug('%c[TODO] '+message, css, optionalParams) 
            : console.debug('%c[TODO] '+message, css);
    }    
     
    // This overrides the todo method and gives the correct line and file,
    // but the color is destroyed.
    // And the optionalParams no longer an array.
    /*private*/ public init() { // public for testing.
        Object.defineProperty(this, "todo", {get: function () {
            return this.level >= this.LOG 
                ? console.debug.bind(console, '%c[TODO]', 'background: #FF0000; color: #0000FF') 
                : function(){};},
            configurable: true
        });     
    }
    
    public setLevel(level: Level) {
        this.level = level;
        this.init();
    }

}
// Test
const logger = new Logger();

logger.todo('normal todo().');
logger.todo('normal todo() with data.', 666, 777);

logger.init(); // This is why init is not called in constructor and public. ;)

logger.todo('modified todo().');
logger.todo('modified todo() with data.', 666, 777);

Screenshot of console.

I also created a jsfiddle with the code.

Is it possible to color the whole message using Object.defineProperty, and if so how?

React Testing Library: Testing boolean state

I am currently writing a test using the testing-library/react.

On the second click of my test, the text should not be in the document, but it is.

Here is the component I am testing:

import { useState } from 'react'
import { InfoType } from '../../constants'

type Props = {
    type: InfoType
}

const HelpWidget = ({ type }: Props) => {
    const [isHover, setHover] = useState<boolean>(false)

    return (
        <div className="help-widget">
            <img
                src={require('../../../public/images/info.svg')}
                onMouseEnter={() => setHover(true)}
                onMouseOut={() => setHover(false)}
                onClick={() => setHover(!isHover)}
            />
            {isHover ? <div className="info">{type}</div> : <div></div>}
        </div>
    )
}

export default HelpWidget

Here is the test I wrote:

import React from 'react'
import { screen, render, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import HelpWidget from '../components/helpWidget/helpWidget'


// Testing if the HelpWidget conditionally renders based on the isHover boolean state.
test('helpWidget conditionally renders to the page', () => {
    const epk4Post = 'Select a persona to post this'
    render(<HelpWidget type={epk4Post} />)
    const imageElement = screen.getByRole("img")
    userEvent.click(imageElement)
    screen.debug()
    expect(screen.getByText(/select a persona to post this/i)).toBeInTheDocument()
    userEvent.click(imageElement)
    screen.debug()
});

And here is what I get when I run screen.debug() to see the DOM output. Here you can clearly see that on the second click, the text is still within the document when it should not be:
enter image description here

Please share your thoughts! Thank you.

Return a res.json and get it with res.render in other router

Im working to return a JSON from the router “/api/product” but render the answer with hbs in the router “/product”. The code works, but is it correct?

My router in this case is: ‘/api/product’

router.get('/', this.controlador.renderProducts);

renderProducts = async (req, res) => {
    try {
      const docs = await this.ProductsDAO.mostrarTodos();

      const productos = docs.map((p) => {
        return new ProductDTO(
          p.id,
          p.precio,
          p.stock
        );
      });

      res.status(200).json({ product:productos });
    } catch (error) {
      logger.error('Error al renderizar productos', error);
      res.status(400).send('Status: No se ha renderizar productos');
    }
  };

Is correct on server.js add this code for it?

app.get('/product', new RequestViews().getProductAll)

`class RequestViews {
  constructor() {
    this.url = 'http://localhost:8080/api/product';
  }

 getProductAll = (req, res, next) => {
    request.get(this.url, (err, response, body) => {
      if (err) {
        return next(err);
      }
      res.render('products', JSON.parse(body));
    });
  }
`
Thanks!!

How to send a custom variable in a flask in Flask to JS/HTML to render an image?

Here is my basic python code to send the variable account name over to the javascript which will render the image.

@app.route('/<username>', methods=['GET', 'POST'])
def user_profile_name(username):
    # return f"welcome to profile page {username}"
    my_friends = database.GET_FRIENDS(connection, username)
    # print(send_string)
    return render_template(f"user_profile.html", friends=my_friends, account_name=username)

Here is my HTML that should go to the file with that name

<div>{{account_name}}</div>
<div id="profile picture">
    <h1>Profile Picture</h1>
    <img src="{{url_for('static', filename='#UserData/{{account_name}}/profile/profile_pic.jpg')}}"  width='200' height='200' />

The image is there, and if I put the name in manually like so, it works, any idea how I can send my name over?

filename='#UserData/MY_NAME_HERE/profile/profile_pic.jpg')}}"  width='200' height='200'

thanks for your time

next.js run build doesnt run my code like run dev

My problem is that this works in run dev, but not run build/start. This is because the use address retuns undefined then geets the connected address. in run dev when i console log I get undefined, undefined, address. How do I fix this because npm start doesnt wait for it to return the address so I always get undefined.

import { useAddress } from "@thirdweb-dev/react";
import Head from 'next/head';
import Link from 'next/link';
import Username from '../components/Username';
import React from "react";

const Home = () => {
    let address = useAddress();

    if (address == undefined) {
        
    }

    console.log(address)
        if (address) {
            return (
                <>
                    <Head>
                        <title>DRUMM3R</title>
                        <link rel="icon" href="/drum.svg" />
                    </Head>
                    <Username address={address} />
                </>
            );
        } else {
            return (
                <>
                    <Head>
                        <title>DRUMM3R</title>
                        <link rel="icon" href="/drum.svg" />                
                    </Head>
                    <Link href="/">
                    <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">click here to log in</a>
                    </Link>
                </>
            );
        }
}

export default Home;
import { useAddress } from "@thirdweb-dev/react";
import Head from 'next/head';
import Link from 'next/link';
import Username from '../components/Username';
import React from "react";

const Home = () => {
    let address = useAddress();

    if (address == undefined) {
        
    }

    console.log(address)
        if (address) {
            return (
                <>
                    <Head>
                        <title>DRUMM3R</title>
                        <link rel="icon" href="/drum.svg" />
                    </Head>
                    <Username address={address} />
                </>
            );
        } else {
            return (
                <>
                    <Head>
                        <title>DRUMM3R</title>
                        <link rel="icon" href="/drum.svg" />                
                    </Head>
                    <Link href="/">
                    <a className="absolute pt-1 text-xl font-semibold transform -translate-x-1/2 top-1/2 left-1/2">click here to log in</a>
                    </Link>
                </>
            );
        }
}

export default Home;

I want to send parameters and headers to url with ajax [duplicate]

$("#submit").on("click", function () {
  let obj = {
    orderNo: 1555,
    userName: "myName",
  };
  $.ajax({
    url: "https://~",
    type: "POST",
    dataType: "json",
    headers: {
      "Content-Type": "application/json",
      "Content-Length": obj.length,
      "Api-Key": "xxx-api-key",
      orderCount: 1,
    },
    data: obj,
    success: function () {
      alert("success");
    },
    error: function () {
      alert("fail");
    },
  });
});

i want to send obj parameters and header key values to url.

when i did that, i got

Access to XMLHttpRequest at ‘URL’ from origin ‘my IP’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

and

POST ‘URL’ net::ERR_FAILED

how can i do this correctly?

Passing user input from html form component to Angular Service

I have a form in my html component:

<form (ngSubmit)="onSubmit()">
    <div class="col-6">
<mat-form-field appearance="outline" [formGroup]="FORM">
  <mat-label>Select a Region</mat-label>
  <mat-select  formControlName="Y">
    <mat-option *ngFor="let Y of locales" [value]="Y.value" >
      {{Y.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>
    </div>
    <div class="col-6">
        <mat-form-field appearance="outline" [formGroup]="FORM">
          <mat-label>Select a Category</mat-label>
          <mat-select  formControlName="category">
            <mat-option *ngFor="let X of Xs" [value]="option.value" >
              {{X.viewValue}}
            </mat-option>
          </mat-select>
        </mat-form-field>
            </div>
           
            <div class="container">
            <button mat-raised-button color="primary" type="submit">Primary</button>
              </div>
    </form>

These valued are passed to my onSubmit(). The this.options.value is able to return the values and my browser console displays the return values.

onSubmit() {
       // Return if form is invalid
       if (this.options.invalid) {
        return;
      }
      console.log('Submit', this.options.value);
    }

I want to add as parameters to a service page I have for an API:

example(): Observable<exampleService[]> {

      return this.httpclient.get<exampleService[]>(`${this.apiUrl}country=us&category=users`);
     }

I am trying to use the user input from the form and fill the “country” and “category” with the values I get returned from the html.
It seems like a basic JS fundamental that I am overthinking or can’t remember learning.

Help appreciated, thanks!

Remove duplicate key from an array of objects

I need help in flattening this array of objects and remove the duplicate SWFIT key for each entry.
Current array:

0: {SWIFT: 'GIBAXXXX', PARTICIPANTS: {…}}
1: {SWIFT: 'GIBAXXXX', SETTLEMENT_BANKS: {…}}
2: {SWIFT: 'IQAMXXXX', ISSUERS: {…}}
3: {SWIFT: 'IQAMXXXX', PARTICIPANTS: {…}}
4: {SWIFT: 'IQAMXXXX', SETTLEMENT_BANKS: {…}}
5: {SWIFT: 'CITIXXXX', ISSUERS: {…}}
6: {SWIFT: 'CITIXXXX', PARTICIPANTS: {…}}
7: {SWIFT: 'CITIXXXX', SETTLEMENT_BANKS: {…}}

So a needed result would be something like this:

0: {SWIFT: 'GIBAXXXX', PARTICIPANTS: {…}, SETTLEMENT_BANKS: {…}}
1: {SWIFT: 'IQAMXXXX', ISSUERS: {…}, PARTICIPANTS: {…}, SETTLEMENT_BANKS: {…}}
2: {SWIFT: 'CITIXXXX', ISSUERS: {…}, PARTICIPANTS: {…}, SETTLEMENT_BANKS: {…}}

I tried various ways to reduce this array into an array of objects but I simply could not figure it out.

How can I merge the subsets of elements in an array that share the same key?

I’m developing a chat system in which all messages are stored in a Mongodb database with the following schema:

const messageSchema = new mongoose.Schema({
    to: String,
    from: String,
    threadTopic: String,
    messages: [
        {
            content: String,
            date: Date,
        }
    ]

})

In this chat system there are “threads” or topics which have a subset of messages. For example, two people could have a conversation on one thread, and those same two people could also have a conversation on a different thread, so I am trying to filter the database output so that it includes all the messages separated by thread.

I am using the following algorithm in order to accomplish this:

var finalResult = [];

for (var i = 0; i < response.length; i++) {
  for (var j = i+1; j < response.length; j++) {

    //Check if there is a match between 2 threadTopics so they can be sonsolidated:
    if (response[i].threadTopic === response[j].threadTopic) {   

      //Extract received messages, i.e. messages sent to the recipient (user)
      const rxMsgs = (response[i].to == "Recipient") ? response[i].messages : response[j].messages

      //Extract messages that the recipient (user) sent
      const txMsgs = (response[i].from = "Recipient") ? response[i].messages : response[j].messages


      const element = {
                        threadName: response[i].threadTopic,
                        msgs: rxMsgs.concat(txMsgs)
                      }

        //append to final consolidated output
        finalOutput = finalOutput.concat(element);
      }
   }
}

In essence, this algorithm takes in an array response containing different threads that appear twice in the array (each time with the from:/to: reversed, i.e.: send or receive), and consolidates all the [messages] arrays belonging to each thread. Is there any way to improve this algorithm so that it performs better than O(n^2)?

Get index of name in 2d array with names separated by commas

I have the following 2d array:

 const sample = [
   ['Name 1', 'Name 2, Name 3', 'Name 4'],
   ['', 'Name 5', 'Name 6, Name 7'],
   ['Name 8, Name 9', 'Name 10', '']
 ]

As you can see, some strings have more than one name (separated by a comma)

I have the following function that return true if input name has an index of 0 or 1 otherwise it returns false:

function indexIsZeroOrOne(arr, name) {
    for (const row of arr) {
        const i = row.indexOf(name)
        if (i === 0 || i === 1) {
          return true
        }  
    }
    return false
  }

It works with strings that have a single name but not with those with multiple names.

How to modify this so that calling, for example: console.log(indexIsZeroOrOne(sample, 'Name 2') would return true?

How to publish a JS package that gracefully fails if an optional peer dependency is not installed

Is there a way to design a JavaScript package for npm that can dynamically import() a third-party npm package, but fail gracefully if that package is not installed as a dependency in the consuming application?

What I want to do is create a React component library that has drag-and-drop capability using react-dnd, but only requires react-dnd as a dependency if the application utilizes that feature. The package.json setup would be something like this:

{
  "name": "my-react-component-lib",
  "devDependencies": {
    "react": "18.2.0",
    "react-dnd": "^16.0.1",
    "react-dnd-html5-backend": "^16.0.1",
    "react-dom": "18.2.0"
  },
  "peerDependecies": {
    "react": ">=16.8.0",
    "react-dnd": "^14.0.0",
    "react-dnd-html5-backend": "^14.0.0"
  },
  "peerDependeciesMeta": {
    "react-dnd": {
      "optional": true
    },
    "react-dnd-html5-backend": {
      "optional": true
    }
  }
}

The main component code switches from a basic, non-DnD component tree to a DnD-enabled component tree (using Hooks from react-dnd) based on a prop the user provides. Something like this:

import { MainComponentBase } from "./MainComponentBase";
import { MainComponentWithDndProvider } from "./MainComponentDnD";
import type { MainComponentProps } from "./types";

export const MainComponent = (props: MainComponentProps) => {
  const key = props.enableDragAndDrop ? "dnd" : "no-dnd";

  if (props.enableDragAndDrop) {
    return <MainComponentWithDndProvider key={key} {...props} />;
  }

  return <MainComponentBase key={key} {...props} />;
};

MainComponentWithDndProvider runs a custom Hook with a run-only-once useEffect that dynamically imports react-dnd and sets a state variable containing the useDrag and useDrop Hooks from that import. Those Hook functions then get passed down to some recursive sub-components that each use them (the non-DnD sub-components do not call them, hence the key prop to make sure we avoid calling a different number of Hooks between renders).

Here is the custom Hook, called useReactDnD:

export type UseReactDnD = typeof import('react-dnd') &
  Pick<typeof import('react-dnd-html5-backend'), 'HTML5Backend'>;

export const useReactDnD = (dndParam?: UseReactDnD) => {
  const [dnd, setDnd] = useState<UseReactDnD | null>(dndParam ?? null);

  useEffect(() => {
    let didCancel = false;

    const getDnD = async () => {
      const [reactDnD, reactDnDHTML5Be] = await Promise.all([
        import('react-dnd').catch(() => null),
        import('react-dnd-html5-backend').catch(() => null),
      ]);

      if (!didCancel) {
        if (reactDnD && reactDnDHTML5Be) {
          setDnd(() => ({ ...reactDnD, HTML5Backend: reactDnDHTML5Be.HTML5Backend }));
        } else {
          // Log a warning to the console about enabling drag-and-drop
          // without installing the necessary dependencies
        }
      }
    };

    if (!dnd) {
      getDnD();
    }

    return () => {
      didCancel = true;
    };
  }, []);

  return dnd;
};

And here is the DnD-enabled component:

export const MainComponentWithDndProvider = (props: MainComponentProps) => {
  const dnd = useReactDnD(props.dnd);
  const key = dnd ? 'dnd' : 'no-dnd';

  if (!dnd) {
    return <MainComponentBase key={key} {...props} />;
  }

  const { DndProvider, HTML5Backend } = dnd;

  return (
    <DndProvider key={key} backend={HTML5Backend} debugMode={props.debugMode}>
      <MainComponentWithoutDndProvider {...{ ...props, dnd }} />
    </DndProvider>
  );
};

(MainComponentWithoutDndProvider just wraps MainComponentBase in DndContext.Consumer and sets up the sub-components.)

If the consuming application decides to utilize the drag-and-drop feature of my-react-component-lib, it can set the enableDragAndDrop prop to true and install react-dnd/react-dnd-html5-backend. If the DnD feature was not to going to be implemented, the extra dependencies would not be necessary as long as the enableDragAndDrop prop remained false or undefined.

This setup seems to work fine when the DnD dependencies are installed in the consuming application, but when they’re not then I run into problems. I’ve only tried it with a Vite-based application, which uses esbuild for the dev server and Rollup for production builds. Both seem to have issues when dynamic imports fail.

For example, when running the app’s dev server with vite, this error appears pointing to the import('react-dnd') line:

[plugin:vite:import-analysis] Failed to resolve import "react-dnd" from "node_modules.vitedepsmy-react-component-lib.js?v=9969840a". Does the file exist?

Is there a better way to do it?

How can I get a specific word between HTML tags with Regex

Given this HTML string:

<p class="">What a <span>classy</span> man!</p>
<p class="tag">He has so much class.</p>

I’d like to use Regex to get the two instances of ‘class’ that are between the HTML tags (i.e. not the class attributes). Note, the word ‘class’ could be anything but the results must not include anything from inside the HTML tags.

Thanks