Find object value with the key stored in a variable [duplicate]

Let’s say I have an array of objects like this:

[
{name:"Mark",surname:"Smith",age:25,status:1},
{name:"Joe",surname:"Hill",age:21,status:7},
{name:"John",surname:"Grant",age:29,status:14},
{name:"Luke",surname:"Davids",age:22,status:9}
]

and I want to sort it by name with something like this:

sort(function(a, b) {
        var textA = a.name.toUpperCase();
        var textB = b.name.toUpperCase();
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
    })

and it works perfectly fine. But what happens if I don’t know the key name directly, and I want to sort it?

I get the key name in a prop, so, in my webApp, if a user clicks on a column in a grid, I get the column name. For example, if he clicks on a surname column, I don’t know how to put the ‘surname’ in my sorting function:

let clickedColumnName = props.column.field;
      data=JSON.parse(sessionStorage.getItem('rnList')).RNList.sort(function(a, b) {
      var textA = a.<clickedColumnName>.toUpperCase();// --> how to put a variable here??
      var textB = b.<clickedColumnName>.toUpperCase();// --> how to put a variable here??
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
    });

How to search using barba.js in wordpress

I am currently using barba.js to create a wordpress theme, but I have no idea how to make it work with the search feature.

If anyone knows how to do this, I would appreciate it if you could let me know.

The current code is as follows.

    // Rewrite in head
    const replaceHead = function(data){
        const head = document.head;
        const newPageRawHead = data.next.html.match(/<head[^>]*>([sS.]*)</head>/i)[0];
        const newPageHead = document.createElement('head');
        newPageHead.innerHTML = newPageRawHead;
    
        const removeHeadTags = [ 
            "meta[name='keywords']"
            ,"meta[name='description']"
            ,"meta[property^='og']"
            ,"meta[name^='twitter']"
            ,"meta[itemprop]"
            ,"link[itemprop]"
            ,"link[rel='prev']"
            ,"link[rel='next']"
            ,"link[rel='canonical']"
        ].join(',');
        
        const headTags = head.querySelectorAll(removeHeadTags)
    
        for(let i = 0; i < headTags.length; i++ ){
            head.removeChild(headTags[i]);
        }
        
        const newHeadTags = newPageHead.querySelectorAll(removeHeadTags)
    
        for(let i = 0; i < newHeadTags.length; i++ ){
            head.appendChild(newHeadTags[i]);
        }
    }

    barba.hooks.beforeEnter((data) => {
        replaceHead(data);
    })

    barba.init({
        transitions: [{
        }]
    });

I found the code to make Contact Form 7 work and thought I could divert it, but gave up because I didn’t know how to do it.

    barba.init({
        transitions: [{
        beforeEnter({ next }) {
            wpSearchFromRun(next);
        }
        }]
    });
    
    function wpSearchFromRun(next) {
        var wpSearchForm = '.search-form';
        var wpForm = $(next.container).find(wpSearchForm);
        if (wpForm.length) {
        $(wpSearchForm).each(function() {
            var $form = $(this);
            //n.init( $form[0] );
        });
        }
    }

Get item and subitem

I need help.

I have this very simple html: https://jsfiddle.net/z8y7Lv2a/

`

<header>
  <ul>
    <li>
      <a href="#">Sobre</a>
    </li>
    <li>
      <a href="#">O que fazemos</a>
    </li>
    <li data-submenu='Nossas sedes'>
      <a href="#">Nossas sedes</a>
      <ul>
        <li>
          <a href="#">Curitiba</a>
        </li>
        <li>
          <a href="#">Acre</a>
        </li>
        <li>
          <a href="#">Salvador</a>
        </li>
      </ul>
    </li>
    <li data-submenu='Serviços'>
      <a href="#">Serviços</a>
      <ul>
        <li>
          <a href="#">Google Analytics</a>
        </li>
        <li>
          <a href="#">Google Tag Manager</a>
        </li>
      </ul>
    </li>
  </ul>
</header>

`

I’m trying to give console when a link is clicked following this rule:

If it is a main link, only the name of the link will appear, for example, clicking on ‘About’ the console will display ‘About’.

By clicking on a submenu, the console should display the parent’s name + the title clicked on, for example: Nossas sedes-Curitiba

Can you help me?

If it is a main link, only the name of the link will appear, for example, clicking on ‘About’ the console will display ‘About’.

By clicking on a submenu, the console should display the parent’s name + the title clicked on, for example: Nossas sedes-Curitiba

API call returns 405 Method not allowed

Hi I’m trying to make a GET request using XMLHttpRequest. The endpoint that I am making the GET request to requires an authorization token and I already includes it. When I try to make the request, I receive ‘405 Method Not Allowed’

var x = new XMLHttpRequest();
token  = '...'
x.open('GET', '/api/v1/experiments/16?format=json');
x.setRequestHeader('Authorization', 'Bearer ' + token);
x.send();
var  datacontainer = [];


x.addEventListener('readystatechange', function(){

    if (x.readyState == 4 && x.status == 200){
        datacontainer = JSON.parse(x.response);
        console.log(datacontainer);
    }
})

Any one has a solution for that?

var x = new XMLHttpRequest();
token  = '...'
x.open('GET', '/api/v1/experiments/16?format=json');
x.setRequestHeader('Authorization', 'Bearer ' + token);
x.send();
var  datacontainer = [];


x.addEventListener('readystatechange', function(){

    if (x.readyState == 4 && x.status == 200){
        datacontainer = JSON.parse(x.response);
        console.log(datacontainer);
    }
})

Carousel need to start from start of the slide on page load

“The following Code i have used for carousel
i am getting this as when page load

HtmlCode

    <div class="arrows">
        <vlocity_cmt-icon class="left-arrow arrow" if:true={showNextButton} icon-name="utility:chevronleft"
            alternative-text="left" onclick={goNext} title="left">
        </vlocity_cmt-icon>

        <vlocity_cmt-icon class="right-arrow arrow" if:true={showPrevButton} icon-name="utility:chevronright"
            alternative-text="right" onclick={goPrev} title="right">
        </vlocity_cmt-icon>

    </div>

JsCode

 setCarousel() {
        for (let index = 0; index <  this.prodSize; index++) {
            
            if (index == this.currentActiveIndex) {
                this.products[index].isPrevNext = this.products[index].isHidden = false
                this.products[index].isActive = true
            } else if (index == this.currentActiveIndex - 1 || index == this.currentActiveIndex + 1) {
                this.products[index].isPrevNext = true;
                this.products[index].isActive = this.products[index].isHidden = false

            } else {
                this.products[index].isHidden = true
                this.products[index].isActive = this.products[index].isPrevNext = false
            }
            if (this.products[index].phone_area_codes) {
                this.products[index].codes = this.products[index].phone_area_codes.join(",")

            }
        }
        this.checkButtonVisibility();
    }

    goPrev() {
        if (this.currentActiveIndex < this.prodSize && (this.currentActiveIndex > 0 || this.prodSize == 1)) {
            this.currentActiveIndex--;
            this.setCarousel();
        }
    }

    goNext() {
        if (this.currentActiveIndex < this.prodSize - 1 && this.currentActiveIndex >= 0) {
            this.currentActiveIndex++;
            console.log('next = '+ this.currentActiveIndex);

            this.setCarousel();
        }
    }

I need to be get this as first when page is load

I Was not able to find that can any one help out

Turn off tooltip flying in animation in Apache ECharts?

For the tooltip I have the following configuration:

tooltip: {
  trigger: 'axis',
  axisPointer: {
    type: 'shadow',
  },
  textStyle: {
    color: this.theme.stockPerformanceChart.tooltip.textStyle.color,
    fontSize: '16',
    fontWeight: '100',
  },
  //position: [10,10],
  backgroundColor: 'white',
  borderColor: 'white',
  borderWidth: 5,
  formatter: (params:any) => `$ ${Math.round(parseInt(params[0].value, 10))}`,
}

And when hovering over one of the bars the tooltip comes flying in from the top right position (The default).

How do we turn off the animation so that the tooltip just appears where the mouse is?

Issue in simple authentication

I created a login page. I am trying to authenticate a user by sending the message from the backend after verifying if the user exists in the database.
Everything is working fine just one problem is that when I login with correct credentials I have to click twice on the submit button for it to work.

import React, { useState } from "react";
import axios from "axios";
const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [auth, setAuth] = useState("Wrong");
  const [mssg, setMssg] = useState("");
  const handleUser = (e) => {
    setUsername(e.target.value);
  };
  const handlePassword = (e) => {
    setPassword(e.target.value);
  };
  const login = (e) => {
    e.preventDefault();
    const user = { username, password };
    console.log(user);
    axios
      .post("http://localhost:5000/auth", user)
      .then((res) => setAuth(res.data.message))
      .catch((err) => console.log(err));
    if (auth === "OK") {
      sessionStorage.setItem("user", username);
      window.location = "/dashboard";
    } else {
      setMssg("Invalid Details. Please try again");
    }
  };
  return (
    <div>
      <form onSubmit={login}>
        <input onChange={handleUser}></input>
        <input type="password" onChange={handlePassword}></input>
        <input type="submit"></input>
      </form>
      <p id="mssg">{mssg}</p>
    </div>
  );
};

export default Login;

When i login with correct credentials, it throws the error. But when i submit again with the same correct credentials, then it redirects me to the dashboard.

Remove item from list React functional component

the code below displays a list after loading data from a backend, how can I cause the values ​​to be removed from the list and the table to be updated

React Code:

import React, { Component } from "react";
import { fileuploadbolla } from "../../services/file";
import Table from "react-bootstrap/Table";
import { Button } from "reactstrap";

function TableArticoli(props) {
  return (
    <Table striped bordered hover editable>
      <thead>
        <tr>
          <th>N° riga</th>
          <th>Codice</th>
          <th>Descrizione</th>
          <th>Prezzo</th>
          <th>Quantita</th>
          <th>Totale</th>
          <th>Edit</th>
        </tr>
      </thead>
      <tbody>
        {props.list.map((item, i) => {
          return [
            <tr>
              <td>{i}</td>
              <td>{item.codart}</td>
              <td>{item.descrizione}</td>
              <td>{item.prezzo}</td>
              <td>{item.prezzolistino}</td>
              <td>{Number(item.prezzolistino) * Number(item.prezzo)}</td>
              <td>
                <Button size="xs" color="danger">
                  Elimina
                </Button>
              </td>
            </tr>,
          ];
        })}
      </tbody>
    </Table>
  );
}

class UploadFileBolla extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image_file: null,
      image_preview: "",
      listarticoli: [],
    };
  }

  handleImagePreview = (e) => {
    let image_as_base64 = URL.createObjectURL(e.target.files[0]);
    let image_as_files = e.target.files[0];

    this.setState({
      image_preview: image_as_base64,
      image_file: image_as_files,
    });
  };

  handleSubmitFile = async () => {
    if (this.state.image_file !== null) {
      let formData = new FormData();
      formData.append("file", this.state.image_file);
      var listarticoli = await fileuploadbolla(formData, "SONEPAR");
      this.setState({ listarticoli: listarticoli.data });
    }
  };

  render() {
    return (
      <div>
        <input type="file" onChange={this.handleImagePreview} />
        <label>Upload file</label>
        <input type="submit" onClick={this.handleSubmitFile} value="Submit" />
        {this.state.listarticoli.length > 0 ? <TableArticoli list={this.state.listarticoli} /> : <></>}
      </div>
    );
  }
}

export default UploadFileBolla;

JS Using tag inside of getElementById Method

Hello everyone Im new on JS,
First of all i created 2 red colored <div> tags named leftarea and rightarea.

div1 which located at left area, has onclick() function buttons.

when button1 is clicked i want to show table1 in the rightarea (div2).
Similarly, when button2 is clicked, i want to show table2 in the rightarea (div2).
Both tables has add/edit/delete functions.

I used getElementById method, so shat buttons which located at div1 (leftarea) can access and create tables in div2 (rightarea).

But when i tried to add/edit/delete properties on tables i cannot use JS objects inside of getElementById method. how can i solve this problem? enter image description here

I tried to use JS objects but it didnt work i want to use JS.

fetch localhost without redirecting to https?

In the development environment, I don’t want to make things complicated by using https and SSL/STL certifications.

I learned how to prevent Google Chrome from redirecting localhost to https, and a JSON object returned after entering http:/localhost:105/hello/ into the Chrome address bar.

What confused me is that the following does not work in the browser console(Inspect->Console):

const url = new URL('http://localhost:105/hello/');
fetch(url).then(response => response.json()).then(json => console.log(json))

The error reads that:

GET https://localhost:105/hello/ net::ERR_SSL_PROTOCOL_ERROR Uncaught
(in promise) TypeError: Failed to fetch
at :1:1

I don’t know why and how the http was redirected to https? How can I prevent that?

Changing an array in Javascript does not update my vue list

I have been building a vue 3 app with nuxt 3. With websockets to update data from the server to the webpage. Now I tried to add a list that updates itself when it gets new data but I cannot get it to work.

To find the problem I have minimized the code to the following example to understand the problem. It still isn’t working. It starts with a one entry array. The page has a button and clicking the button adds another entry. But the list does not update.

This is inside a vue component that is shown on the main app.vue.

The commented blocks were from other tries when scribbeling around to get it to work.

Code:

<script setup>

import '/js/control.js';
import '/js/websocket';
// let items = [{
//   "timestamp": "b",
//   "Message":"Hallo",
//   "SourceInfo": "",
//   "Counter":0
// }];
data: () => (items = 
 [{
   "timestamp": "b",
   "Message":"Hallo",
   "SourceInfo": "",
   "Counter":0
 }])

 const items = 
 [{
   "timestamp": "b",
   "Message":"Hallo",
   "SourceInfo": "",
   "Counter":0
 }]
// export default {
//   data: {
// let    items = 
//  [{
//    "timestamp": "b",
//    "Message":"Hallo",
//    "SourceInfo": "",
//    "Counter":0
//  }]


function more() {
  console.log(items);
  items.push({
  "timestamp": "r",
  "Message":"b",
  "SourceInfo": "",
  "Counter":0
});

}
</script>

<template>
  <div class="someclass">
    <ul>
      <li v-for="item in items">
        {{item.timestamp}} - {{item.Message}}
      </li>
    </ul>
    <button @click="more">more</button>
  </div>
</template>

<style>
.someclass {
  /* background-image: url('/SW4_EG.jpg'); */
  /* background-repeat: no-repeat;
  width: 983px;
  height: 537px; */
  position: relative;
}
</style>

Sum of two random numbers with Javascript

I’m trying to create a program with Javascript that prints two random numbers and calculates their sum. It should be really easy, but for some reason I can’t get the program to work. I’ve got the program to print random numbers, but I can’t get it to add the numbers together. What am I doing wrong?


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
    <body>

        <p id="myBtn"></p>
        <p id="number1"></p>
        <p id="number2"></p>

        <button id="myBtn" onclick="myFunction()">Get random number</button>


        <script>

            var allNumbers = 0;

            function myFunction() {
                num1 = document.getElementById("number1").innerHTML = Math.floor(Math.random() * (7 - 1) + 1);
                num2 = document.getElementById("number2").innerHTML = Math.floor(Math.random() * (7 - 1) + 1);
                var inTotal = num1 + num2;
                var allNumbers =+ inTotal;
            }

            document.write(allNumbers);

        </script>

    </body>
</html>

Send Invites to emails after creating google sheet using google sheet api from node.js

Hi I am creating a google sheet from Google Sheets API v4. I want to give access to my system users for that google sheet. is there any google sheet API for this? even for enterprise packages?

const service = google.sheets({ version: 'v4', auth: oauthClient });
const newSpreadSheet = await service.spreadsheets.create({
  requestBody: {
    properties: {
      title: 'Test Sheet 0001',
    },
  },
});

I have tried to add users to the protected range but still, those email didn’t get access to google sheet

await service.spreadsheets.batchUpdate({
  spreadsheetId: spredSheetId,
  requestBody: {
    requests: [
      {
        addProtectedRange: {
          protectedRange: {
            range: {
              sheetId: 0,
              startRowIndex: 0,
              endRowIndex: 10,
              startColumnIndex: 0,
              endColumnIndex: 5,
            },
            description: 'trying to give read or write access for emails',
            editors: {
              users: ['[email protected]'],
            },
          },
        },
      },
    ],
  },
});

can you please suggest or i have to create & move to shared drive folder?