Javascript spreading an object’s properties array at specific index

Given a react hook and an object with array properties, I want to find a way to update the hook by using the spread operator at a specific properties index. Here is an example where I want to take the index 0 of the array in each property and spread it

const [{ a, b, c }, setState] = useState({ a : 'x', b : 'x', c : 'y' })

const temp = {
    a : ['x1', 'y1'],
    b : ['x2', 'y2'],
    c : ['x3', 'y3']
}

setState({...temp[0]})

/* Expected to be spread onto
*  setState({
*    a : 'x1',
*    b : 'x2',
*    c : 'x3'
*  })
*/

How would I achieve this? Am I looking at the wrong place to begin with by using the spread operator?

Things I have tried

  • Tried looking into .filter() but I was not able to make it work
  • Tried playing around with the [0] position and other syntaxes but with no success either

TTake array Index values in onClick event

how to write an onClick event in my react app to take array index in this code? I just want to get array index as a output

This is my array in JSON file.

{
        "Women": [
            {
                "id"  : 1,
                "name"  : "See All",
                "children" : [""]
            },
            {
                "id"  : 2,
                "name"  : "Clothes",
                "children" : [ "Coats & jackets" , "Suits & blazers" , "Skirts"]
            },
            {
                "id"  : 3,
                "name"  : "Shoes",
                "children" : [ "Boots" , "Flats" , "Ankle boots"]
            },
            {
                "id"  : 4,
                "name"  : "Bags",
                "children" : [ "Handbags" , "Backpacks" , "Clutches"]
            },
            {
                "id"  : 5,
                "name"  : "Accessories",
                "children" : [ "Jewelry" , "Belts" , "Scarves & Shawls"]
            },
            {
                "id"  : 6,
                "name"  : "Beauty",
                "children" : [ "Make Up" , "Face Care" , "Hand Care"]
            }
        ]
}

This is my array import

const Women = AdminCatData.Women.map ((data) => {
    
  return(
    { 
      ...data,
    }
  )
  }

)

For Loop is not redefining what’s supposed to be defined

I have this for loop in which I’m trying to replace an index in underlineArr with a character and whenever I try to redefine it so It saves the current variable so I’m able to access it and change it later, nothing is being saved, It keeps using the default array while I’m trying to get the newly edited array.

For Loop:

       const content = collected.content.toLowerCase();
           for (let i = 0; i < underlineArr.length; i++) {
               msg = underlineArr[i] = word[i] == content && underlineArr[i] == "_" ? content : "_";
           }
           msg = underlineArr.join(" ");
           console.log(msg);

This is the underlineArr constant: https://i.stack.imgur.com/vtzj2.png

This is the word constant: "French Toast", Please note the constant is random from an array I created.

Lastly, collected.content is just a string returned.

The output: Output

Expected output:

_ r _ _ _ _ _ _ _ _ _ _
_ r e _ _ _ _ _ _ _ _ _
_ r e n _ _ _ _ _ _ _ _
_ r e n c _ _ _ _ _ _ _
.....

Uncaught TypeError: FormData.set: 1 is not a valid argument count for any overload

I am trying to a input a number through input tag and after pressing the submit button the state has to update and the updated state is used here sankeyData.splice({ count });. and useState default value should be 3. I am getting Uncaught TypeError: FormData.set: 1 is not a valid argument count for any overload.. And the default state is also not recognizing. I dont know where i am doing wrong.

import React, { useState } from "react";
import Chart from "react-google-charts";
import { data } from "./csvjson";

// const sankeyData = [];
// var sank = [];
// var output = data.map(function (obj) {
//   return Object.keys(obj).slice(1).map(function (key) {
//     return obj[key];
//   });
// });

const First = () => {
  const [count, setCount] = useState(0);
  console.log(count);
  const onSubmit = (e) => {
    e.preventDefault();
    const formdata = new FormData();
    console.log(formdata.set(count));
  };

  const sankeyData = [
    ["From", "To", "Weight"],
    ["since", "None", 23],
    ["gallery", "None", 2],
    ["turnofthetwentiethcentury", "None", 1],
    ["turn", "None", 45],
    ["likedis", "None", 1],
    ["profound", "Male", 1],
    ["Semblance", "None", 1],
    ["Africans", "Male", 2],
    ["Guided", "None", 1],
    ["Golinski", "None", 1],
    ["implosion", "Male", 1],
    ["Searchs", "None", 1],
    ["concerning", "Female", 1],
    ["families", "Male", 2],
  ];

  sankeyData.splice({ count });

  return (
    <div>
      <h2>React Simple Sankey Chart Example</h2>
      <Chart
        width={700}
        height={"350px"}
        chartType="Sankey"
        loader={<div>Loading Chart</div>}
        data={sankeyData}
        rootProps={{ "data-testid": "1" }}
      />
      <div>
        <form noValidate onSubmit={onSubmit}>
          <input value={setCount} />
          <button type="submit">SUBMIT</button>
        </form>
      </div>
    </div>
  );
};

export default First;

Async Function Not refreshing

This function works for a single data item but it should keep refreshing every few seconds. How does this repeat?

   async function get_iss() {
       const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544');
       const data = await response.json();
       document.getElementById("ISSdata").innerHTML = data.altitude;
       Textbox1.value = data.longitude;
       Textbox2.value = data.latitude;
   }
   get_iss();>

How to convert images produced by html canvas to .ai(adobe illustrator) file format in either frontend or backend process?

I’m developing a webapp to edit photos and trying to download them as adobe illustrator (.ai) file format.

The webapp has two parts frontend and backend. React for frontend, and Django restframework for backend.
The photos are edited within a html canvas element, and the canvas is controlled by JavaScript.

Th code below converts the canvas element to a dataURL, so I can see the compiled image after hitting the url. The url shows it is png format.

var canvas = document.getElementById("myCanvas");
var dataURL = canvas.toDataURL();

And the url looks like this.

data:image/png;base64,iVBORw0KGgoAAA...

Is there any way to convert the canvas image to .ai(adobe illustrator) file format using ether JavaScript, React for frontend, or python for backend process?

how do i properly assign a price, then calculate price by quantity? javascript

(the javascript is in a separate file for tidy purposes)

this is my first time posting a question

im learning to create a website, i have multiple inputs in the html.
I also want to output the total for both individually and as well as
all together in an estimate within the bottom of the website.

individually ItemPrice * Quantity;

all together = total price;

hope this makes sense??## Heading ##


 // Calculating Function for Tier3
function price(Tier3) {
    var Tier1 = document.getElementById("Tier3");//Getting ID
    Tier3 = 1.4;

    var Tier1 = document.getElementById("Tier2");//Getting ID
    Tier2 = 1.6;

    var Tier1 = document.getElementById("Tier1");//Getting ID
    Tier1 = 1.8;

    var RAM = document.getElementById("RAM");//Getting ID
    RAM = 3.45; //assigning value

    var vCPU = document.getElementsByID("vCPU"); //Getting ID
    vCPU = 2.54; // assigning price?

    var price = parseFloat($('#price').text()) || 0;
    var qty = parseInt($('#quantity').val());
    var total = price * qty;
    $('#total').text(total);

}

update price according to quantity

I have a small problem with my buttons for a school project.
When I update the quantity by typing it in the form the price updates but when I try to change the quantity by clicking on my buttons it doesn’t work.
Here is the HTML (I used bootstrap 5)

<span id="price">6.99</span> 
<div class="num-block skin-5">
<div class="num-block skin-2 pt-2">
    <div class="num-in">
      <span class="minus dis" id="decrease" onclick="decreaseValue()"></span>
      <input type="number" id="qty" min="0" value="0"/>
      <span class="plus" id="increase" onclick="increaseValue()"></span>
    </div>
  </div>
</div>
<button id="changingprice" class="rounded buttonshad buttonstyling bg-primary text-light mx-5">Add $<span>0.00</span></button>

And here is the javascript

function increaseValue() {
value = parseInt(document.getElementById("qty").value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById("qty").value = value;
}
function decreaseValue() {
value = parseInt(document.getElementById("qty").value, 10);
value = isNaN(value) ? 0 : value;
value < 1 ? value = 1 : '';
value--;
document.getElementById('qty').value = value;
}
let basePrice = document.getElementById("price").innerHTML;
document.querySelector("#qty").addEventListener("change", function(){
document.querySelector("#changingprice span").innerText = (basePrice * this.value).toFixed(2)
})

Hope someone can help me, have a good day !

Replacing divs with vanilla javascript

I’m looking for a way to replace child element, in the code below, I’m trying to replace child-div1 by child-div2, then child-div-2 by child-div-3, then 3 by 1 etc, looping while I click on a button. (This code is an example, in my actual code inside the parent-div there is 4 others divs with 1 span element in each..)

HTML CODE EXAMPLE:

    <button onclick="replaceContent()"></button>

<div class="parent-div">
            <div id="child-div-1">
                <span>hello</span>
            </div>
        </div>
<div class="parent-div">
                <div id="child-div-2">
                    <span>world</span>
                </div>
            </div>
<div class="parent-div">
                <div id="child-div-3">
                    <span>test</span>
                </div>
            </div>

JAVASCRIPT ideas & tests :

let parentDiv = document.getElementByClassName('parent-div');
let childOne = document.getElementById('child-div-1');
let childTwo = document.getElementById('child-div-2');
let childThree = document.getElementById('child-div-3');

function replaceContent() {
then I am stuck here;
}

I don’t know how to setup this :
replaceChild(newChild, oldChild);

Thank you for your help !

Nodejs amfjs – Error: No AMF3 type with ID 239

I am making a node app that uses the npm library amfjs to decode a file. I am getting this error: (node:88188) UnhandledPromiseRejectionWarning: Error: No AMF3 type with ID 239

Here’s my code:

async function getDefpack(id) {
  try {
    var url = `https://ajcontent.akamaized.net/${version}/defPacks/${hashIt(id)}`
    var response = await fetch(url).then(response => response.text())
    if (response.includes("Access Denied")) {
      log("That defPack doesn't exist.", "Doesn't Exist.")
    }
    else {
      let rs = new Readable();
      let decoder = new amfjs.AMFDecoder(rs);
      rs.push(new Buffer.from(response)).toString()
      rs.push(null)
      var obj = decoder.decode();
      delete obj.__class;
      if (stringArray.hasOwnProperty(id)) {
        for (var property in obj) {
        var key = stringArray[id];
        if (!stringsJSON.hasOwnProperty(obj[property][key])) continue;
        obj[property].name = stringsJSON[obj[property][key]];
        }
      }
    return JSON.stringify(obj, null, 2);
    }
  }
  catch (err){
    log("nnnn" + err)
  }
}

The error points to my code let decoder = new amfjs.AMFDecoder(rs);, though I am not familiar enough with this library to know what’s going on, so any help would be greatly appreciated!

at Object.fromId (node_modulesamfjslibtypes.js:168:15)
at AMFDecoder.deserialize (node_modulesamfjslibdecoder.js:58:24)
at AMFDecoder.decode (node_modulesamfjslibdecoder.js:53:19)

Tuple vs hard coded string

We have this code at our work, which i wanted to know the difference between it and just manually typing out the same thing.

const tuple = <T extends string[]>(...args: T) => args;
const strings = tuple(
  'blabla',
  'default',
  'standard'
);

export type Strings = typeof strings[number];

When i hover over “Strings”, it basically is type Strings = 'blabla' | 'default' | 'standard'

My question is, why not just simply type out the samething?

type Strings = 'blabla' | 'default' | 'standard';

Instead of all the tuple stuff? I can’t see a difference, but if someone could explain why we’re using this Tuple function that would be great

Why this simple code keeps showing fail to load [duplicate]

I have this simple code which trying to make and download a pdf file by using JS blob.

let text = 'download'
function make(){
    const data = new Blob([text],{ type: 'application/pdf' })
    document.querySelector('a').href = window.URL.createObjectURL(data);
}
make()
<a download>Download</a>

It does work, but problem is when I open the downloaded file, it shows fail to load pdf file.enter image description here

There are several questions and similar ways to download pdf file use blob, but I can’t figure out what I did wrong and how to fix it.

What I am missing?

Any suggestions and answer will be appreicated.

How avoid duplicate on mongoDB with filter

Im beginner on javascript & mongodb, i wanted a way to filter a all adref variable from my jList

adref is a unique string of characters which allows me to differentiate to avoid duplicates on my database.
So i made a loop to make that filter but i don’t know exactly how to do it on JS, because I usually use python

My goal is, if the adref value exists on DB pass to the next one or else insert in the db.
I use pass statement, because I don’t know the equivalent in JS…

const jList = [];

result.data.results.map((elem) =>{
  let info = {
        title: elem.title,
        description: elem.description,
        adref: elem.adref
   }
     
     jList.push(info)
    });

  })

  //Connect to database
  const uri = 'mongodb+srv://...mongodb.net/MyCollection?retryWrites=true&w=majority'

  mongoose.connect(uri, { useNewUrlParser: true })
  const db = mongoose.connection
  db.once('open', _ => {
    console.log('Database connected:', uri)
  })

  db.on('error', err => {
    console.error('connection error:', err)
  })

  
 //don't know what is equivalent of python pass statement
 const pass = () => {}

  

 for (let info of jList) {
    if db.collection.find({ $and: [ { adref: {$exists: true } } ]}) {
      pass()
    }
      else{
        db.collection.insertMany( { title: elem.title, description: elem.title, adref: elem.adref,} )
    }

}

Thanks