How to get 1 to n key value in an array of objects and push them to a new array?(Javascript) [duplicate]

I have an array of objects,

[
 {trial1: 'a1', trial2: 'a2', trial3: 'a3'},
 {trial1: 'b1', trial2: 'b2', trial3: 'b3'},
 {trial1: 'c1', trial2: 'c2', trial3: 'c3'},
 ]

How do I get an array of arrays like this

[
 ['a1','a2','a3'],
 ['b1','b2','b3'],
 ['c1','c2','c3']
]

And also an array like this

[
 ['a1','b1','c1'],
 ['a2','b2','c2'],
 ['a3','b3','c3']
]

File Upload in WebdriverIO where we need to access the file explorer in Windows

This is a field where either I have to access the file explorer in Windows and then select the file to upload or, I have to drag and drop the file to upload the file. I am using the following code in WebdriverIO, but the file upload in not happening.

 const fileUpload = $("//div[@id='customer_information']//div[@aria-hidden='true']");
 const path = require('path');
 const filePath = path.join(__dirname, '../../Test Data/Captute0.png');
 //const filePath = path.join(__dirname, 'F:\WebDriverIO\Capture.png');
 fileUpload.setValue(filePath);

What should I use for the first parameter of the .apply() method when calling it within an XMLHttpRequest?

I’m trying to write a function which will act on an array of data passed into it using AJAX. It’s not doing anything, and the last thing left that I can find that I might be doing wrong is the first parameter of my .apply() call (i.e. the owner of my underlyingFunction() method).

Here’s my code:

function XMLfunction(targetElement,param1,param2) {
    var workingArray = new Array(targetElement);
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var parser = new DOMParser();
            var xml = parser.parseFromString(this.responseText,"text/xml");
            for (var i = 0; i < xml.childNodes[0].childNodes.length; i++) {
                workingArray.push(xml.childNodes[0].childNodes[i].innerHTML);
            }
            alert (workingArray); // workingArray looks exactly like it's supposed to
            underlyingFunction().apply(this,workingArray);  // underlyingFunction() works perfectly when called directly in a script
            alert ("applied"); // XMLfunction() stops before it gets to this line
        }
    }
    request.open("GET","myURL.php?param1="+param1+"&param2="+param2,true);
    request.send();
}

The first parameter of .apply() here is this, but I have tried using document and, out of desperation, window as well. What should it be? Or what else am I doing wrong?

Dynamic select option is not working anymore after change to new firebase project

This is a follow-up question from a question that I asked and answered before:

https://stackoverflow.com/a/69762698/16136444

In summary, if I pick a choice on the 1st v-select, it will only display limited choices on the 2nd v-select, which are related to the first choice that I made on the 1st v-select. Then, after choices are made on the 2nd v-select, it will auto-generate and display the code assigned to that 2nd choice on the 3rd v-select.

Before it was successfully done on my testing firebase project and it works and it still is. But after I created a new firebase project and do the same thing, it did not work out.

  1. Old firestore collection on my testing project
  • Scope of Works > All docs contain scope value > Specialization > docs containing specialization & code

old firestore on my testing project 1
old firestore on my testing project 2

  1. New firestore collection created for production project
    new firestore on my production project 1
    new firestore on my production project 2

So, the only thing that is changed is I removed spacing & use PascalCase for the name of the collection and documents. Other than it is all just the same. So now I used .collection("ScopeOfWork") (new) instead of .collection("Scope of Works")(old) to read from firestore

What could possibly be wrong with it? Any advice?

Thank you :))

What is the fastest way to tell whether a web resource is a text file?

Some Chrome URLs are just text files that are rendered as monospaced text files.
As an example, this is the Public Suffix List (https://publicsuffix.org/list/public_suffix_list.dat), and looks like this:

Public Suffix List

You can also get to this type of page by going to any raw GitHub user content, like https://raw.githubusercontent.com/github/docs/main/README.md.

I am building a Chrome extension and want to check what type of document the page has in the content script. My current code is this, and describes the HTML wrapper that I see around text:

const documentIsText = document.head.innerHTML.length === 0
        && document.body.children.length === 1
        && document.body.children[0].nodeName.toLowerCase() === 'pre'

This is the HTML wrapper I see:

<html data-lt-installed="true">
  <head></head>
  <body>
    <pre style="word-wrap: break-word; white-space: pre-wrap;">
    "Lots of text!"
    </pre>
  </body>
</html>

It seems like there should be some property of document that should answer this question.

It’s possible to check the document’s response header for content-type: text/plain with a background script, but I want to check for this information in a content script.

Question

What is the fastest way to definitively check that the page you are looking at is just text with client-side JavaScript after page load?

I want to put swr data into setState[]

I have code like this.

const { data } = useSWR('/api/data', fetcher);
const [contents, setcontents] = useState<Array<string>>([]);

json is like this

console.log(data) 

Text: Array(5)
0: {id: 1, title: '123', content: 'hi'}
1: {id: 2, title: '1234', content: 'qq'}
2: {id: 3, title: '12323', content: 'ww'}
3: {id: 4, title: '123124', content: 'ee.'}
4: {id: 5, title: '24124', content: 'rr.'}

I want to output content in json as map and put it in setContents.

I think you can create a function and output it as a map, then call setContents and put a value in the return value, but it doesn’t seem to work..

How can I put json array contents in setContents??

Copy to clipboard javascript navigator.clipboard.write

Not able copy to clipboard
It is a color picker random generator

on click of button it not copy hexcode to the clipboard

it is giving error Uncaught  typeerror copyText.select is not function

navigator​.​clipboard​.​write​Text or navigator​.​clipboard​.​write​

 const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
 const btn = document.getElementById("button");
 const color = document.querySelector(".color");
 btn.addEventListener("click", function() {
    let hexColor = "#";
    for (let i = 0; i < 6; i++) {
        hexColor += hex[getRandomNumber()];
    }
    color.textContent = hexColor;
    document.body.style.backgroundColor = hexColor;
 });

 function getRandomNumber() {
    return Math.floor(Math.random() * hex.length);
 }

 function myFunction() {
    let copyText = document.getElementById("color-code");
    console.log("copytext" + copyText);
    copyText.select();
    navigator.clipboard.write(copyText.value);
    alert("Copied the text: " + copyText.value);
 }
 <section class="hero  is-large">
     <div class="hero-body">
         <div class="container has-text-centered">
             <div class="columns is-mobile">
                 <div class="column is-half is-offset-one-quarter">
                     <div class="card">
                         <div class="card-header field is-grouped">
                             <h3 class="card-header-title is-inline">
                                 <span> Background Color <span class="tag is-large  is-pulled-right color" id="color-code">hexcode </span>
                                 </span>
                             </h3>
                             <button class="button p-4 m-4" id="copyColorHex" onclick="myFunction()">
                                 <span class="icon is-small is-right">
                                     <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 " fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                         <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                                     </svg>
                                 </span>
                             </button>
                         </div>
                     </div>
                 </div>
             </div>
         </div>
         <div class="container has-text-centered">
             <div class="p-5 ">
                 <button class="button " id="button">click me</button>
             </div>
         </div>
     </div>
 </section>

Thanks in advanced

How to remove duplicate n (line break) from a string and keep only one?

I have a string like this:

This is a sentence.n This is sentence 2.nnnnnn This is sentence 3.nn And here is the final sentence.

What I want to is:

This is a sentence.n This is sentence 2.n This is sentence 3.n And here is the final sentence.

I want to remove all duplicated n characters from a string but keep only one left, is it possible to do like that in javascript ?

Developer Tools Console showing only final values

I have the following code that I run in the console:

// cache the starting array - 50 elements
let asTheyWere = selDocument.fields.field;
// create the new object
let nf = {};
$j.each(selDocument.fields.field[selDocument.fields.field.length - 1], function(a, b){
    nf[a] = b;
});
// make a change and add the object to the array
for(i = 0; i < 5; i++) {
    nf.name = `test me ${i}`;
    selDocument.fields.field.push(nf);
}
// assign the array to a new variable - now at 55 elements
let asTheyAre = selDocument.fields.field;
// check the values
console.log(asTheyWere);
console.log(asTheyAre);

I know that the console doesn’t update until the code is finished, so all variables are logged with their final value. I had thought that using different variables would avoid that, but asTheyWere and asTheyAre are the same, showing 55 elements (the first should have 50), AND the values appended to the end of the array are all the same as well: they should be ‘test me 0’, ‘test me 1’, ‘test me 2’ and so on, but they’re all ‘test me 4’.

What’s going on? How can I watch the progress and see accurate values?

Redirect in react-router-dom V6

I need to navigate back to the original requested URL after login.

For example, user enters www.example.com/settings as user is not authenticated, it will navigate to login page www.example.com/login.

Once authenticated, it should navigate back to www.example.com/settings automatically.

My original approach with react-router-dom v5 is quite simple:

const PrivateRoute = ({ isLoggedIn, component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        isLoggedIn? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{ pathname: `/login/${props.location.search}`, state: { from: props.location } }}
          />
        )
      }
    />
  );
};


<PrivateRoute exact isLoggedIn={isLoggedIn} path="/settings" component={Settings} />

Can some one tell me how to do that in v6? Thanks in advance

How to use innerHTML safely?

Instead of retyping repeated codes for a side bar in Javascript, I made a sidebar function which is used to populate similar codes for every pages. it looks like this:

function addSidebarTemplate(){
      const template = document.createElement('template');
      template.innerHTML = `<aside class="aside-container">
                            <header>
                <a href="."> link here</a>
                <a class="mr-1" href="#">
                    <i class="fab fa-linkedin"></i>
                </a>
                <a class="mr-1" href="#">
                    <i class="fab fa-facebook"></i>
                </a>
                <a class="mr-1" href="#">
                    <i class="fab fa-github"></i>
                </a>
                 </header>`
       document.querySelector('#sidebar').appendChild(sidebar.content);

There are other elements below this code. But none of them requires user’s input. I just wonder is this safe to use innerHTML in this case? If not, is there better way to insert the side bar like this?

Thanks

Why is unshift() returning a different value than push() if I am targeting the first element in the former and the last element in the latter?

I have a function for Project Euler #7. Towards the end, I changed the code from primeArray.push(i); to primeArray.unshift(i) and return primeArray[primeArray.length - 1]; to return primeArray[0];. This altered the return. In the former. It returned the correct answer, 104021, while the latter returned 20001, which is not even prime. I do not understand why that is.

function primeFinder(primeTarget) {
  //since 2 is the only even prime, putting it here saves us some effort in checking primality by just iterating over the odd numbers
  //it also helps the for loop since we are only interested in checking for divisors among previous primes.
  let primeArray = [2];
  let i = 3;

  while (primeArray.length < primeTarget) {
    let primeLogger = false;
    //We don't need to check for divisibility by 2, so j can equal 1
    for (j = 1; j < primeArray.length && primeArray[j] < Math.sqrt(i); j++) {
      if (i % primeArray[j] === 0) {
        primeLogger = true;
        //Since we have found a divisor and changed primeLogger, we can exit the loop
        break;
      }
    }
    //Where the break goes to, and also where the for loop goes to once finishes
    if (primeLogger === false) {
      primeArray.push(i);
    }
    i += 2;
  }
  return primeArray[primeArray.length - 1];
}
console.log(primeFinder(10001));