Merge two arrays with different set of strings using es6 functional programming

I’ve converted csv based text files to arrays containing headers and rows and now I want to convert them into given below solution. Can anybody do this using methods like .map(), .reduce() or whatever.

Arrays I have look alike:

let header = ['a', 'b', 'c', 'd'];
let rows = ['1,2,3,4', '5,6,7,8', '9,0,1,2'];

The result I want:

[
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
  },
  {
    a: 5,
    b: 6,
    c: 7,
    d: 8,
  },
  {
    a: 9,
    b: 0,
    c: 1,
    d: 2,
  },
]

I was able to do this using for loop but that wasn’t the appropriate solution for es6.

Above I’ve mentioned some dummy arrays, right now the actual code is:

const recordReader = content => {
    let weatherRecords = [];
    let rows = content.split('n');
    let headers = rows.shift().split(',');

    for (let row = 0; row < rows.length; row++) {
        let weatherReading = {};
        if (!rows[row]) {
            continue;
        }
        let record = rows[row].split(',');

        for (let column = 0; column < headers.length; column++) {
            weatherReading[headers[column]] = record[column];
        }

        weatherRecords.push(weatherReading);
    }
    return weatherRecords;
};

Optional chaining doesn’t work on Node 16.4

I have tried this syntax in VSCode and Coderpad (both use Node version 16.4).

let x = {}
x?.something.foo

As far as my understanding goes, this code shouldn’t throw an error now, but return undefined. The feature optional chaining should be available in Node v14+ but for some reason it doesn’t work in my VSCode and also in Coderpad.

Thought why?

React change subdomain dynamically

I am using react to build an application and there is one API integrated which gives me subdomain in the response. I am saving the whole response in organization object variable.

How do I configure my application to switch to that subdomain once its retrieved? I went through some articles around the web but couldn’t figure it out. I have tried like this also:

  useEffect(() => {
    if (organization.org.subdomain !== null && organization.org.subdomain !== undefined) {
      window.location.assign(organization.org.subdomain)
    }
  },[organization.org.subdomain])

Note: I am using hash-router.

How to convert array to object and assign value in javascript

i have array value and object for data mapping. reduce method is not working for object mapping, here is sample data.

the array value is

let array = [ "payload", "offer", "application_id" ]

object value is

let data = {
                organization_id: 4002400004,
                organization_name: 'Velocity Global Integration Sandbox',
                action: 'offer_updated',
                payload: {
                    offer: {
                        id: 4524843004,
                        application_id: 31948577004,
                        user_id: 4123647004,
                        version: 1,
                        sent_on: null,
                        resolved_at: '2022-05-19T06:21:25.084Z',
                        start_date: '2022-05-17',
                        notes: null,
                        job_id: 4298940004,
                        offer_status: 'Accepted'
                    },
                    "resume": {
                        name: "manikandan"
                    }
                }
            }

need to form new object with the response

let payload = {
    offer: {
        application_id: 343645656
    }
}

Vue.js-Failed to load resource: the server responded with a status of 401 (Unauthorized)

I’m currently working on a project that collects payment info(like the products the client wants to buy, and how much that product costs) and client details(client name, client address, client credit card info, etc.) and I need to access Stripe’s online payment system for the purchase. However, during my trial run, every time I try to click all “Pay”, I keep getting notifications that something went wrong. I checked the terminal and it keeps displaying this error:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

I’m also using Django’s rest framework for my backend development, and it keeps displaying this

 HTTP 401 Unauthorized
    Allow: POST, OPTIONS
    Content-Type: application/json
    Vary: Accept
    WWW-Authenticate: Token
    
    {
        "detail": "Authentication credentials were not provided."
    }

This is the code I think the problem is located in:

<template>
  <div class="page-checkout">
    <div class="columns is-multiline">
      <div class="column is-12">
        <h1 class="title">Checkout</h1>
      </div>

      <div class="column is-12 box">
        <table class="table is-fullwidth">
          <thead>
            <tr>
              <th>Product</th>
              <th>Price</th>
              <th>Quantity</th>
              <th>Total</th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="item in cart.items" v-bind:key="item.product.id">
              <td>{{ item.product.name }}</td>
              <td>{{ item.product.price }}</td>
              <td>{{ item.quantity }}</td>
              <td>₱{{ getItemTotal(item).toFixed(2) }}</td>
            </tr>
          </tbody>

          <tfoot>
            <tr>
              <td colspan="2">Total</td>
              <td>{{ cartTotalLength }}</td>
              <td>₱{{ cartTotalPrice.toFixed(2) }}</td>
            </tr>
          </tfoot>
        </table>
      </div>

      <div class="column is-12 box">
        <h2 class="subtitle">Shipping Details</h2>

        <p class="has-text-grey mb-4">* All fields required</p>

        <div class="columns is-multiline">
          <div class="column is-6">
            <div class="field">
              <label>First Name*</label>
              <div class="control">
                <input type="text" class="input" v-model="first_name">
              </div>
            </div>

            <div class="field">
              <label>Last Name*</label>
              <div class="control">
                <input type="text" class="input" v-model="last_name">
              </div>
            </div>

            <div class="field">
              <label>E-mail*</label>
              <div class="control">
                <input type="email" class="input" v-model="email">
              </div>
            </div>

            <div class="field">
              <label>Phone*</label>
              <div class="control">
                <input type="text" class="input" v-model="phone">
              </div>
            </div>
          </div>

          <div class="column is-6">
            <div class="field">
              <label>Address*</label>
              <div class="control">
                <input type="text" class="input" v-model="address">
              </div>
            </div>

            <div class="field">
              <label>Zipcode*</label>
              <div class="control">
                <input type="text" class="input" v-model="zipcode">
              </div>
            </div>

            <div class="field">
              <label>Place*</label>
              <div class="control">
                <input type="email" class="input" v-model="place">
              </div>
            </div>
          </div>
        </div>

        <div class="notification is-danger mt-4" v-if="errors.length">
          <p v-for="error in errors" v-bind:key="error">{{ error }}</p>
        </div>

        <hr>

        <div id="card-element" class="mb-5"></div>

        <template v-if="cartTotalLength">
          <hr>

          <button class="button is-dark" @click="submitForm">Pay with Stripe</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: "Checkout",
  data() {
    return {
      cart: {
        items: []
      },
      stripe: {},
      card: {},
      first_name: '',
      last_name: '',
      email: '',
      phone: '',
      address: '',
      zipcode: '',
      place: '',
      errors: []
    }
  },
  mounted() {
    document.title = ' The "GO BUY IT" page | Bjackets '

    this.cart = this.$store.state.cart

    if (this.cartTotalLength > 0) {
      this.stripe = Stripe('pk_test_51L3bhzFMIo7cZ677WbW384hMgVFcLs9E0x4sLocwajtGbnZIlplXoWSlSKr1IM89tWOCFYIBOWPpcF8OzBWGCnZR00MN1fPAGW')
      const elements = this.stripe.elements();
      this.card = elements.create('card', { hidePostalCode: true })

      this.card.mount('#card-element')
    }
  },
  methods: {
    getItemTotal(item) {
      return item.quantity * item.product.price
    },
    submitForm() {
      this.errors = []

      if (this.first_name === '') {
        this.errors.push('The First Name feild is empty. Please fill-out the space with your first name. For example, "Gaylord"')
      }

      if (this.last_name === '') {
        this.errors.push('The Last Name feild is empty. Please fill-out the space with your last name. For example, "Gaylord"')
      }

      if (this.email === '') {
        this.errors.push('The email feild is missing. Please fill-out the space with your email. For example, "[email protected]"')
      }

      if (this.phone === '') {
        this.errors.push('The phone feild is missing. Please fill-out the space with your contact number. For example, "123-456-7890"')
      }

      if (this.address === '') {
        this.errors.push('The address feild is missing. Please fill-out the space with your address. In other words, tell me where you live.')
      }

      if (this.zipcode === '') {
        this.errors.push('The zipcode feild is missing.')
      }

      if (this.place === '') {
        this.errors.push('Are you located in Lozun, Visayas, Mindanao?')
      }

      if (!this.errors.length) {
        this.$store.commit('setIsLoading', true)

        this.stripe.createToken(this.card).then(result => {
          if (result.error) {
            this.$store.commit('setIsLoading', false)

            this.errors.push('Something went wrong with Stripe. Please try again')

            console.log(result.error.message)
          } else {
            this.stripeTokenHandler(result.token)
          }
        })
      }
    },
    async stripeTokenHandler(token) {
      const items = []

      for (let i = 0; i < this.cart.items.length; i++) {
        const item = this.cart.items[i]
        const obj = {
          product: item.product.id,
          quantity: item.quantity,
          price: item.product.price * item.quantity
        }

        items.push(obj)
      }

      const data = {
        'first_name': this.first_name,
        'last_name': this.last_name,
        'email': this.email,
        'address': this.address,
        'zipcode': this.zipcode,
        'place': this.place,
        'phone': this.phone,
        'items': items,
        'stripe_token': token.id
      }

      await axios
        .post('/api/v1/checkout/', data)
        .then(response => {
          this.$store.commit('clearCart')
          this.$router.push('/cart/success')
        })
        .catch(error => {
          this.errors.push('Something went wrong. Please try again')
          console.log(error)
        })
      this.$store.commit('setIsLoading', false)
    }
  },
  computed: {
    cartTotalPrice() {
      return this.cart.items.reduce((acc, curVal) => {
        return acc += curVal.product.price * curVal.quantity
      }, 0)
    },
    cartTotalLength() {
      return this.cart.items.reduce((acc, curVal) => {
        return acc += curVal.quantity
      }, 0)
    },
  }
}
</script>

How to fix SSL error with NodeJS HTTPS server?

I’m new to Stack Overflow and this is my first question, so please bear with me. I never had to ask a question until I had a problem and couldn’t find a solution. Anyways, my problem is my Node JS HTTPS server that I use to host my website has a problem where when the client requests a resource such as a video or an image, it’s a 50% chance that the resource will properly load for the client. The times it doesn’t load I get an SSL error in the console (for example, net::ERR_SSL_PROTOCOL_ERROR 200 (OK)). Sometimes it will load, sometimes it won’t. I don’t know if I have a misconfiguration with my server or not, but I need to get this fixed. I need the resource to load for the client 100% of the time. Any help would be great.

Here’s how my server is configured.

// Redirect HTTP traffic to HTTPS
http.createServer((req, res) => {
    if (req.headers.host === 'domain.com') {
        let redirectUrl = `https://${req.headers.host}${req.url}`;
        res.statusCode = 301;
        res.setHeader('Location', redirectUrl);
        res.end();
        return;
    }
    reqHandler(req, res);
}).listen(80);

// HTTPS server
const server = https.createServer({
    cert: readFileSync('/path/to/cert.pem').toString(),
    key: readFileSync('/path/to/key.pem').toString(),
    ca: readFileSync('/path/to/chain.pem').toString()
}, reqHandler);
server.listen(443);

Git – Renaming a Branch Name, Encounter an error

I have given the branch name as below while creating the new branch:

git checkout -b "working_with_controllers(APIs_Logic)"

At them time of creation it didn’t throw an error stating

this is the wrong format

But when trying to switch or rename a branch using command

git branch -m working_with_controllers(APIs_Logic)  new-branch working_with_controllers

Showing the error

bash: syntax error near unexpected token `('

Can any one help me with the solution please

How to hide DIV’s parent in JS with a specific content

I’m trying to hide a DIV’s parent when a certain DIV contains a specific text.

An example. This DIV I want to stay:

<div class="report-per-day">
<div class="report-day">26 May 2022</div>
<div class="status-report-rows">
<p class="report__headline">This is our report</p>
</div>
</div>
</div>

But I want to hide this whole DIV, because there’s a DIV .mt-2, which contains “No new incident.”

<div class="report-per-day">
<div class="report-day">25 May 2022</div>
<div class="mt-2" style="display: none;">
<small class="text-muted">No new incident.</small>
</div>
</div>
</div>

I have this Java Script, but it only hides the .mt-2. I’d also like to hide its 2 parents, .report-per-day and .report-day

Do you guys happen to have any suggestions? Thanks a lot!

const divs = document.getElementsByClassName('mt-2');

for (let x = 0; x < divs.length; x++) {
    const div = divs[x];
    const content = div.textContent.trim();
  
    if (content == 'No incidents reported.') {
        div.style.display = 'none';
    }
}

How to rewrite this template processor without eval?

I currently have a template read from a file into tstr and I replace placeholders in it like so:

const obj = { main: 3 };
const func = () => { const a = 2; };

let tstr = `

<fname func>

<fbare func>

<var obj.main>

`;

tstr = tstr.replace(/<var ([^>]+)>/g, function () { return eval(arguments[1]) });
tstr = tstr.replace(/<fbare ([^>]+)>/g, function () { return eval(arguments[1]).toString() });
tstr = tstr.replace(/<fname ([^>]+)>/g, function () { return arguments[1] + ' = ' + eval(arguments[1]).toString()  });


console.log(tstr);

Is there a simple way to rewrite these replacements without eval?

MUI: The value provided to Autocomplete is invalid. None of the options match with `””`

enter image description here

When a value is entered in the input of the autocomplete component I get this warning that I can’t remove…
This is what my input looks like

 <Autocomplete
            id="cboAdresse"
            sx={{ width: 100 + "%", fontFamily: "Poppins Bold" }}
            getOptionLabel={(option) =>
              typeof option === "string" ? option : option.label
            }
            filterOptions={(x) => {
              return x;
            }}
            options={lstadresse}
            isOptionEqualToValue={(option, value) =>
              value.label === option.label
            }
            autoComplete
            includeInputInList
            filterSelectedOptions
            value={adresse}
            noOptionsText="Aucune adresse trouvée"
            onChange={(event, newValue) => {
              setLstAdresse(
                newValue.name ? [newValue.name, ...lstadresse] : lstadresse
              );
              setAdresse(newValue.name);
              if (newValue.name != "") {
                setVille(newValue.city);
                setCodePostal(newValue.postcode);
              }
            }}
            onInputChange={(event, newInputValue) => {
              setInputRue(newInputValue);
            }}
            renderInput={(params) => (
              <div
                ref={params.InputProps.ref}
                className="login-block__input form_input_white"
              >
                <input
                  type="text"
                  name="adresse"
                  placeholder="Adresse"
                  {...params.inputProps}
                />
              </div>
            )}
      />

We can see that I have integrated the IsOptionEqualToValue parameter without solving the problem. During my research other people have faced this problem and solved it with what I wrote with the IsOptionEqualToValue. If anyone has a solution I’m interested. Thanks in advance.

Why doesn’t the constructor property show up in for/in loop or Object.keys but works with getOwnPropertyNames?

So here’s the code:

function foo() {};

let obj = new foo();

console.log(Object.getOwnPropertyNames(obj)); //  []
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)));
//  [ 'constructor' ]

We create and instance of foo on line 3. On line 5, we output the own properties of instance obj which outputs and empty array. On line 6, we output the properties on the prototype of instance obj which displays an array containing the constructor property.

However, when I try to check for the constructor property using Object.keys or for/in loop, it doesn’t show up. Why?

function foo() {};

let obj = new foo();

console.log(Object.keys(Object.getPrototypeOf(obj)));   //  []

for (let key in Object.getPrototypeOf(obj)) {
  console.log(key);
}

How to find multple results in Arrays with JavaScript?

How i make this?

const arrays = [
    { servername: "MyServer", owner: "Evelyn" },
    { servername: "Minecraft Server", owner: "Maria" },
    { servername: "You really are reading this? xd", owner: "RaymondG" }
];

const Data = arrays.find(data => data.servername.includes("a"));
// Result: { servername: "Minecraft Server", owner: "Maria" }

// I want get this: [{ servername: "Minecraft Server", owner: "Maria" }, { servername: "You really are reading this? xd", owner: "RaymondG" }];

In summary, I would like to know how to obtain the data of an Array that contains certain requirements, I have tried with for-of, but the problem with this is that with large data, it usually takes a long time…

how to convert html webpage to PDF and download it In Javascript/Vuejs from client-side? That PDF should be editable and not just an image

I am using Vue.js (Vue2) Project and i need to give a functionality of export PDF for the webPage/Html content which is displayed already for the user. there are lots of libraries like jsPDF, html2pdf, etc etc but none of them allows me to select the text or edit the PDF in Online PDF editor.
And 1 more thing that the html content is already rendered in the browser and that html I want to export as a PDF so basically it should be operated totaly from client Side and not from the server Side.
I have heard about pspdfKit but the documentation is not clear.