select html element by its full html tag – JS

I am looking for a way to be able to select an HTML element by its tag, like:

document.querySelector("<div id='myDiv'>hello world</div>")
//instead of: document.querySelector("#myDiv")

However, this code returns an error. The code should return the HTML element.

Does anybody know a way to achieve this? (vanilla JS preferred)

Nuxt doesn’t minify the html entirely

While using nuxt generate, nuxt minifies the html as follows,

<!doctype html>
<html data-n-head-ssr lang="en" data-n-head="%7B%22lang%22:%7B%22ssr%22:%22en%22%7D%7D">
  <head>
    <title>Website</title><meta data-n-head="ssr" charset="utf-8"><meta data-n-head="ssr" name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta data-n-head="ssr" name="description" content="Website"><meta data-n-head="ssr" name="format-detection" content="telephone=no"><link data-n-head="ssr" rel="icon" type="image/x-icon" href="/favicon.ico">

As you can see the line breaks after <!doctype html>, <html>, <head> aren’t removed. Why is that? And how do I remove the line breaks? Thanks.

nuxt.config.js

import path from "path"

export default {
  target: "static",
  // Target: https://go.nuxtjs.dev/config-target
  // target: "static",
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: "Website",
    htmlAttrs: {
      lang: "en",
    },
    meta: [
      { charset: "utf-8" },
      {
        name: "viewport",
        content: "width=device-width, initial-scale=1, shrink-to-fit=no",
      },
      {
        name: "description",
        content: "Website",
      },
      { name: "format-detection", content: "telephone=no" },
    ],
    link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }],
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [],

  router: {
    trailingSlash: false,
  },

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/content
    "@nuxt/content",
  ],

  // Content module configuration: https://go.nuxtjs.dev/config-content
  content: {},

  // Build Configuration: https://go.nuxtjs.dev/config-build

  alias: {
    "@/": path.resolve(__dirname, "/"),
  },
}

A HTML form contain two select tags in php

There are two onchange functions are created for both tag in HTML form. This onchange function is used to show the other option input. For my condition, one of the onchange function is working but the another one is not defined. May I know how to solve the problem?

Filter Object based on Keys and compare with array

I currently have an object containing key with multiple values.

I also have an array containing a simple key check i.e. ["random", "three"].

I want to return mainData but only with the object and the data from whats in the array i.e. ["random", "three"]

Current Code:

const mainData = {
    random: {
        name: "Random Entity",
        date: "05/04/2022",
        startTime: "19:00",
        finishTime: "00:00",
    },
    one: {
        name: "One Entity",
        date: "16/04/2022",
        startTime: "16:00",
        finishTime: "20:00",
    },
    three: {
        name: "Three Entity",
        date: "19/04/2022",
        startTime: "10:00",
        finishTime: "11:00",
    },
};

export default mainData;

Desired Output

const mainData = {
    random: {
        name: "Random Entity",
        date: "05/04/2022",
        startTime: "19:00",
        finishTime: "00:00",
    },
    three: {
        name: "Three Entity",
        date: "19/04/2022",
        startTime: "10:00",
        finishTime: "11:00",
    },
};

Attempt:

let filterKey = 'random';
const result = Object.entries(mainData).filter(([k, v]) => k== filterKey);

This works only as a single search, not an array search.

redirect IE to Edge can only do one time?

I am trying to redirect IE users to Edge since IE is retiring.

My website is built by Angular 7 and I put this code in ngOnInit()

const ua = window.navigator.userAgent;

if (ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident") > 0) {
    window.location.href = "microsoft-edge:" + window.location.href;

    setTimeout(function () {
        window.location.href = "https://support.microsoft.com/zh-tw/office/%E9%80%99%E5%80%8B%E7%B6%B2%E7%AB%99%E5%9C%A8-internet-explorer-%E4%B8%AD%E7%84%A1%E6%B3%95%E4%BD%BF%E7%94%A8-8f5fc675-cd47-414c-9535-12821ddfc554";
    }, 0);
}

my steps:

  1. open IE and type http://localhost:4200/index into the URL bar

→ IE window: redirect to Microsoft support page

→ new Edge window open with http://localhost:4200/index

  1. close Edge window and keep IE window open and retype http://localhost:4200/index into IE

→ IE window: redirect to Microsoft support page

no Edge window open

but if I close both IE window and Edge window and open a new IE window and do the whole thing again, it works fine.

IE version: 1903

Edge version: 98.0.1108.62

Does anyone know why and how can I fix it? thanks.

How to pull certain field names from a REST API using ExpressJS and Axios

So I have a set of code that can pull the whole external API with this code:

//endpoint that will fetch data from an external API
app.get("/externalapi", (req, res) => {
    
    let apiURL = 'https://herokuapp.com/api/v1/data';
      
      axios.get(apiURL)
          .then(response => {
              
              res.status(200).json(response.data);
          })
          .catch((err) => {
              res.status(500).json({ message: err });
          });
  });

Part of the data that is generated via Postman is this (used as an example):

{
    "data": [
        {
            "first_name": "Fiona",
            "last_name": "Smith",
            "phone_number": "987-3595-89",
            "mental_health_referral": false,
            "date_last_mental_health_referal": "02/09/2018T00:00:00.0000Z",
            "legal_councel_referal": true,
            "CHW_id": 6866318
        },
        {
            "first_name": "Richard",
            "last_name": "Stewart",
            "phone_number": "281-0394-41",
            "mental_health_referral": true,
            "date_last_mental_health_referal": "03/23/2018T00:00:00.0000Z",
            "legal_councel_referal": false,
            "CHW_id": 9241074
        },
        {
            "first_name": "Andrew",
            "last_name": "Stevens",
            "phone_number": "068-8173-37",
            "mental_health_referral": true,
            "date_last_mental_health_referal": "03/30/2018T00:00:00.0000Z",
            "legal_councel_referal": true,
            "CHW_id": 9241074
        }
}

Now my goal is to generate only Fiona’s information, which is the first data. My outline for the URL is:

GET https://herokuapp.com/api/v1/data/{{first_name}}/{{last_name}}/{{phone_number}}

I have tried something like:

https://herokuapp.com/api/v1/data?first_name=Fiona&last_name=Smith&phone_number=987-3595-89

But I am not getting the result I want and when I run the get request on Postman, I still get all the results of the API. What am I missing?

How can i render only first image from my array of objects?

I have an array of objects which contain products details. On the object, there is an images array of objects property where all the images with id are there. I am trying to render only the first image from that array of objects. I have tried to set 0 indexes to render only the first object but I got an error.

My database:

[
{
    _id: "asdasdds",
    title: "Title",
    reg_price: string
    images: [
        {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
 {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
    ]
},
{
    _id: "asdasdds",
    title: "Title",
    reg_price: string
    images: [
        {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
 {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
{
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
    ]
}
]

Here is my code: when I set 0 index product.images[0] I got map doesn’t exist error.

{
        products.map(product => {
            return <tr>
                <td className="px-5 py-5 border-b border-gray-200 bg-white text-sm">
                    <div className="flex items-center">
                        <div className="flex-shrink-0 w-10 h-10">

                            {                  
                                product.images[0].map(({ src }) => <img className="w-full h-full rounded-full"
                                    src={src}
                                    alt="" />)
                            }
                        </div>

                    </div>

Way to update specific values in Bootstrap cards

I apologize for the amateur question here, however, I am experiencing some issues with a quick demo website I am creating for a friend.

The purpose of the site is to take the total of all “credit card values”, and then divide it by the total amount of “points” there are to arrive at the “points per dollar”

Once that is done, I’d like to multiply the “points per dollar” by the total amount of “points” that are specified in the dropdown menu by the user, and then update all of the cards that have something selected to be the proper math with their point values.

I’ve successfully done all the math and created functions, but I am unsure how to actually apply it to the specific cards that need it.

I’ve created functions to do the math, and update the header numbers, just not apply it to the respective cards.

My code can be found here

My website is running on an express.js server with e.js as the templating engine, with bootstrap and jquery.

Any suggestions/help would be very much appreciated.

DiscordJS V13 doesnt react to dms

I have this very basic code for a very basic discord bot

since the new discord.js version 13 you need to declare intents.

I tried doing that using the bitmap 32767 (basically declaring all intents), however the bot doesnt trigger the “messageCreate” event when a message is send
in the dms it only works in servers.

All privileged gateway intents on the developer site have been set to true.

What am I missing?

const Discord = require("discord.js");
const allIntents = new Discord.Intents(32767);
const client = new Discord.Client({ intents: allIntents });


require("dotenv").config();
const botName = "Miku";

client.once("ready", () => {
    //gets executed once at the start of the bot
    console.log(botName + " is online!");
});


client.on("messageCreate", (message) => {
    console.log("got a message");
});


(async() => {
    //bot connects with Discord api
    client.login(process.env.TOKEN);
})();

How to customize Monaco syntax highlighting using functions?

I want to enable the end user to customize the syntax highlighting of the Monaco editor. I know there’s defineTheme but I want individual functions for each part of the Monaco colors like the code I have below.

SetBackground = function(background) {
                monaco.editor.defineTheme('Custom', {
                base: 'vs-dark',
                inherit: false,
                rules: [],
                colors: {
                    'editor.background': `#${background}`,
                }
                });
            }

This code works for setting the background but when I use my other function for setting the foreground the background reverts to that of vs-dark. Is there any way to write functions like these that add on to an existing theme and update it using user input?

Trying to make snake object eat another object p5.js

I’m a very new programmer and have been learning through p5.js. My current project is a basic snake game. I don’t care about lengthening my snake just yet. I want to make my snake (currently just a green rect) eat food (the red rect) without the growing of the snake added yet. Though I can’t figure out a way to do this. I attached part of my code incase you were trying to review that. Thanks a lot !

var x = 100
var y = 100
var xSpeed = 10
var ySpeed = 0
let randomization=5;
let startGame = true;
let food;
let snake;
let endscreen = false

function setup() {
    createCanvas(400, 400);

    textSize(30)
    textStyle(BOLD)
    textAlign(CENTER,CENTER);
  w = floor(width/randomization);
  h = floor(height/randomization);
  frameRate(10);


eat();


}
  function eat(){
  let x = floor(random(w));
  let y = floor(random(h));
  food = createVector(x, y);
  
}

function draw() {
    if (startGame ==true) { // GAME START SCREEN
        background(0,0,0)
        fill(255,255,255)
        text('Click The Screen to Start',200,100);
    } else { 
        x = x + xSpeed
        if (x > 400) {
            xSpeed *= -1; 
        
        } 
        y = y + ySpeed
        background(220);
        fill(0,255,0)
        rect(x,y,20,20); // SNAKE
    fill(255,0,0);
    rect(food.x,food.y, 10, 10);  // FOOD
    }

how to call a functional method in a component class render method? getting Uncaught TypeError: Cannot read property ‘value’ of null in React

I am creating a web application using both component and functional classes. I created the regsiter and login using component class but I was struggling to create the searchbar using component class so I created it using a functional class. I’m confused as to where I’m meant to call the search function? The function itself has no issue running on its own when its just a functional class and I dont have any of the code for the register or login so I dont believe the error has to do with the function itself. However when I add the code for register and login and call the function from render it doesnt seem to work and returns as null, is there anything I’m missing? Is it possible I’m supposed to be doing something with componentDidMount()?

import React, { Component, useState } from "react";
import axios from 'axios';
import { Switch, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import styled from "styled-components";

import AuthService from "./services/auth.service";

import Login from "./components/login.component";
import Register from "./components/register.component";
import Home from "./components/home.component";
import Profile from "./components/profile.component";
import BoardUser from "./components/board-user.component";
import BoardCreator from "./components/board-creator.component";
import BoardAdmin from "./components/board-admin.component";
import MovieList from "./components/movie-list.component";

// import AuthVerify from "./common/auth-verify";
import EventBus from "./common/EventBus";


const Container = styled.div`
  display: flex;
  flex-direction: column;
`;
const AppName = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
`;
const Header = styled.div`
  background-color: black;
  color: white;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  padding: 10px;
  font-size: 25px;
  font-weight: bold;
  box-shadow: 0 3px 6px 0 #555;
`;
const SearchBox = styled.div`
  display: flex;
  flex-direction: row;
  padding: 10px 10px;
  border-radius: 6px;
  margin-left: 20px;
  width: 50%;
  background-color: white;
`;

const SearchInput = styled.input`
  color: black;
  font-size: 16px;
  font-weight: bold;
  border: none;
  outline: none;
  margin-left: 15px;
`;

const MovieListContainer = styled.div`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  padding: 30px;
  gap: 25px;
  justify-content: space-evenly;;
`;

class App extends Component {
  constructor(props) {
    super(props);
    this.logOut = this.logOut.bind(this);

    this.state = {
      showCreatorBoard: false,
      showAdminBoard: false,
      currentUser: undefined,
      timeoutId: "",
      updateTimeoutId: ""
    };
}

  componentDidMount() {
    const user = AuthService.getCurrentUser();

    if (user) {
      this.setState({
        currentUser: user,
        showCreatorBoard: user.roles.includes("ROLE_MODERATOR"),
        showAdminBoard: user.roles.includes("ROLE_ADMIN"),
      });
    }
    
    EventBus.on("logout", () => {
      this.logOut();
    });

    
  }

  componentWillUnmount() {
    EventBus.remove("logout");
  }

  logOut() {
    AuthService.logout();
    this.setState({
      showCreatorBoard: false,
      showAdminBoard: false,
      currentUser: undefined,
    });
  }

  render() {
    const { currentUser, showCreatorBoard, showAdminBoard} = this.state;

    return (
      <div>
        <nav className="navbar navbar-expand navbar-dark bg-dark">
          <Link to={"/"} className="navbar-brand">
            Movie App
          </Link>
          <div className="navbar-nav mr-auto">
            <li className="nav-item">
              <Link to={"/home"} className="nav-link">
                Home
              </Link>
            </li>

            {showCreatorBoard && (
              <li className="nav-item">
                <Link to={"/mod"} className="nav-link">
                  Moderator Board
                </Link>
              </li>
            )}

            {showAdminBoard && (
              <li className="nav-item">
                <Link to={"/admin"} className="nav-link">
                  Admin Board
                </Link>
              </li>
            )}

            {currentUser && (
              <li className="nav-item">
                <Link to={"/user"} className="nav-link">
                  User
                </Link>              
              </li>
            )}
          </div>         
          <Search />
          

          {currentUser ? (
            <div className="navbar-nav ml-auto">
              <li className="nav-item">
                <Link to={"/profile"} className="nav-link">
                  {currentUser.username}
                </Link>
              </li>
              <li className="nav-item">
                <a href="/login" className="nav-link" onClick={this.logOut}>
                  LogOut
                </a>
              </li>
            </div>
          ) : (
            <div className="navbar-nav ml-auto">
              <li className="nav-item">
                <Link to={"/login"} className="nav-link">
                  Login
                </Link>
              </li>

              <li className="nav-item">
                <Link to={"/register"} className="nav-link">
                  Sign Up
                </Link>
              </li>
            </div>
          )}
        </nav>

        <div className="container mt-3">
          <Switch>
            <Route exact path={["/", "/home"]} component={Home} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/register" component={Register} />
            <Route exact path="/profile" component={Profile} />
            <Route path="/films" 
                  component={MovieList}
                  
                  /> 
            <Route path="/user" component={BoardUser} />
            <Route path="/creator" component={BoardCreator} />
            <Route path="/admin" component={BoardAdmin} />
          </Switch>
        </div>
        <MovieListContainer>
          <MovieList></MovieList>
          <MovieList></MovieList>
          <MovieList></MovieList>
          <MovieList></MovieList>
        </MovieListContainer>

        { /*<AuthVerify logOut={this.logOut}/> */ }
      </div>
    );
  }
}

function Search() {
  const [searchQuery, setSearchQuery] = useState(""); 
  const [timeoutId, updateTimeoutId] = useState();

  const fetchData = async (searchString) => {
    const response = await axios.get(`https://api.themoviedb.org/3/search/movie?api_key=f134dfeac1ebb17feefa58d7f94e94cd&language=en-US&query=${searchString}&page=1&include_adult=false`);
    console.log(response);
  };

  const onTextChange = (e) => {
    clearTimeout(timeoutId);
    setSearchQuery(e.target.value);
    const timeout = setTimeout(() => fetchData(e.target.value), 500);
    updateTimeoutId(timeout);
  };

  return(
    <div> 
      <SearchBox>
      <SearchInput placeholder="SEARCH" value={searchQuery} onChange={onTextChange}></SearchInput>
      </SearchBox></div>
  );
}

export default App;

Fetching data when using mouse hover

this code works but you need to select or click the data first before displaying the data. What i want to do is to use mouse hover and data will display because there are similar data upon entering and displaying the data so i think i should use mouse hover so you can see the difference of the data. Your help is much appreciated

enter image description here

  <tr class='tr_input'>
        <td><textarea rows="3" type='text' name='sear[]' class='form-control sear' id='sear_1'></textarea></td>
        <td><textarea rows="3" type='text' name='fee[]'  class='form-control fee' id='fee_1' ></textarea></td>
        <td><textarea rows="3" type='text' name='description[]'  class='form-control description' id='description_1' ></textarea></td>
        <td><textarea rows="3" type='text' name='office[]' class='form-control office' id='office_1' ></textarea></td>
        <td><input rows="3" type='text' name='amount[]'  class='form-control amount payment' id='amount_1' ></td>
        <td><input rows="3" type="text" id='fpay0' name='quantity[]' class="form-control qty payment" autocomplete="off"/></td>
        <td><input type="text" class="form-control numeric_value0 subtotals" name="subtotal[]" id='subtotal_1' autocomplete="off"/></td>
   </tr>
    <script type="text/javascript">
        $(document).ready(function(){

            $(document).on('keydown', '.sear', function() {
                
                var id = this.id;
                var splitid = id.split('_');
                var index = splitid[1];

                $( '#'+id ).autocomplete({
                    source: function( request, response ) {
                        $.ajax({
                            url: "getDetails.php",
                            type: 'post',
                            dataType: "json",
                            data: {
                                search: request.term,request:1
                            },
                            success: function( data ) {
                                response( data );
                            }
                        });
                    },
                    select: function (event, ui) {
                        $(this).val(ui.item.label); // display the selected text
                        var userid = ui.item.value; // selected id to input

                        // AJAX
                        $.ajax({
                            url: 'getDetails.php',
                            type: 'post',
                            data: {userid:userid,request:2},
                            dataType: 'json',
                            success:function(response){
                                
                                var len = response.length;

                                if(len > 0){
                                    var id = response[0]['id'];
                                    var fee = response[0]['fee'];
                                    var description = response[0]['description'];
                                    var office = response[0]['office'];
                                    var amount = response[0]['amount'];
                                    var qty = response[0]['qty'];
                                    var subtotal = response[0]['subtotal'];

                                    document.getElementById('fee_'+index).value = fee;
                                    document.getElementById('description_'+index).value = description;
                                    document.getElementById('office_'+index).value = office;
                                    document.getElementById('amount_'+index).value = amount;
                                    
                                }
                                
                            }
                        });

                        return false;
                    }
                });
            });
            
            // Add more
            
            var index = 2;
         
            $('#addmore').click(function(){
                // Get last id 
                var lastarp_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
                var split_id = lastarp_id.split('_');

                // New index
                var index = Number(split_id[1]) + 1;

                // Create row with input elements
                var html = "<tr class='tr_input'><td><textarea rows='3' type='text' name='sear[]' class='form-control sear' id='sear_"+index+"'></textarea></td><td><textarea rows='3' type='text' name='fee[]' class='form-control fee' id='fee_"+index+"' ></textarea></td><td><textarea rows='3' type='text' name='description[]' class='form-control description' id='description_"+index+"' ></textarea></td><td><textarea rows='3' type='text' class='form-control office' id='office_"+index+"' ></textarea></td><td><input rows='3' type='text' name='amount[]' class='form-control input-md amount paym' id='amount_"+index+"' ></td><td><input type='text' name='quantity[]' class='form-control qty paym' id='quantity_"+index+"' ></td><td><input type='text' class='form-control subtotals numeric_value' name='subtotal[]' id='subtotal_"+index+"' ></td></tr>";

                // Append data
                $('tbody').append(html);
                
                $('.paym').keyup(function() {
                    var ids = $(this).attr("id").split("_");
                    // alert(ids[1]);
                    var sum = 0;
                    var f = $('#amount_'+ids[1]).val();
                    var p = $('#quantity_'+ids[1]).val(); 
                    
                    sum = Number(f) * Number(p);
                    $('#subtotal_'+ids[1]).val(sum.toFixed(2));
                    var sums = 0;
                    $('.subtotals').each(function() {
                        
                         sums += Number($(this).val());

                    });
                    sums = sums;
                    $('#total').val(sums.toFixed(2));
                    $('#tes').val(combines($('#total').val()));
                });
                index=index+1;;
            });
            
            $( "#delete" ).click(function() {
                var rowCount = $('#tab_logic tr').length;
                var del = rowCount - 2;
                var ind = del-1;
                if(del==2){
                }else{
                    $("#tab_logic tr:eq("+ind+")").remove();
                    del=del-1;
                    var sums = 0;
                    $('.subtotals').each(function() {
                        
                         sums += Number($(this).val());

                    });
                    sums = sums;
                    $('#total').val(sums.toFixed(2));
                    $('#tes').val(combines($('#total').val()));
                }
            });
            //end
            //start
            $('.numeric_value').keyup(function() {
                var sum = 0;
                $('.numeric_value').each(function() {
                    
                     sum += Number($(this).val());

                });
                sums = sums;
                $('#total').val(sum.toFixed(2));
                $('#tes').val(combines($('#total').val()));
            });
            
            
            $('.payment').keyup(function() {
                var sum = 0;
                    var f = $('#fpay0').val();
                    var p = $('#amount_1').val(); 
                    
                    sum = Number(f) * Number(p);
                    $('.numeric_value0').val(sum.toFixed(2));
                    var sums = 0;
                    $('.subtotals').each(function() {
                        
                         sums += Number($(this).val());

                    });
                    sums = sums;
                    $('#total').val(sums.toFixed(2));
                    $('#tes').val(combines($('#total').val()));
                
            });
            
            //endold
        })
    </script>

Set every object’s array it’s x index element

So I have an object like so that contains properties that are either and object (containing other objects untill it’s not an object anymore) or an array of strings of text from english and french:

let langs = {
    click : ["Click here", "Clique ici"],
    stat : ["Fonction status", "Status de la fonction"],
    no : ["Disabled", "Désactivé"],
    ping : {
        base : ["Pinging...", "Calcul du ping..."],
        result : ["Search complete, my latency is", "Recherche terminée, ma latence est de"]
    },
    kick : {
        error : {
            msg : [
            "I can't find this member, please check its writing or @!",
            "Je n'est pas trouvé ce membre, veuillez vérifier son écriture ou son @ !"
            ]
        }
    }
}

My question : Is there a way to dynamically copy that object so that my output would be the exact same but with the arrays only be a string which is either the first or second element?
I know how to set an object’s property to (for example) the first element

let langs = { a : ["1","2"], b : ["3","4"] }
Object.keys(langs).forEach(n =>{
  langs[n] = langs[n][0]
})
console.log(langs)

But the object “langs” can not only be an array but also an object containing arrays or objects containing objects of arrays etc..
Would be awesome to have a function for this..

let langs = { a : ["1","2"], b : ["3","4"] };
langs = onlySelectIndexElement(langs,0) // Or 1 if I want the second element etc..

Jquery if/else remove class on dynamic data [duplicate]

Hello im trying to append and remove a css class depending on what value is in the div

if the value is equal to custom now i add a class that removes the :after appended to my text.

I want to reapply the class if it otherwise.

setInterval(function() {
  $('.monthappend').each(function() {
    var text = $(this).text();
    $(this).text(text.replace('$0', 'CUSTOM'));

    if ($(this).text() == 'CUSTOM') {
      $('.monthappend').addClass('without-after-element');
    } else {
      $('.monthappend').removeClass('without-after-element');
    }
  });
}, 1000);

this else statement didnt work… i tried adding another interval check after this one

<script>
setInterval(function() {
  $('.monthappend').each(function() {
    if ($(this).text() != 'CUSTOM') {
      $('.monthappend').removeClass('without-after-element');
    }
  });
}, 2000);
</script>

but this just caused the appended text to appear and reappear in a loop.

Please help!

site im working this code on
https://staging-homecarepulse.kinsta.cloud/pricing-calc-2/