Quero criar uma única array com os objetos que vem de uma requisição [closed]

Eu consigo obter alguns objeto em uma requisição porem gostaria de colocar todos esses objetos em uma única array. Quando crio uma array e coloco todos os objeto parece q são criada uma array para cada objeto é estranho e isso buga a minha mente.

const veiculos = dados => {

    var dev = []

    let fetchPro = fetch(`${baseUrl}/api/devices/${dados.deviceId}`, {
        headers: {
            cookie: cookie
        },
    }).then(reponse => reponse.json())
    .then(reponse => {
        dados.Prefixo = reponse.name;
        dev.push(dados)
    })

    Promise.resolve(fetchPro)
    .then(() => log.log(dev))

}

Obtenho esse resultado….

enter image description here

Eu so queria colocar os objetos dentro de uma única array por por exemplo

enter image description here

how to setState for an array of fulfilled promises

In my react app, I am retrieving some data from firebase , but when I try to store the items in my state it stores only the first item of the fulfilled promises ,

const HomePage = (props) => {
  const [events ,setEvents] = React.useState([])
const fetchGames=async()=>{
    const DB =await db.collection('game').get()

    DB.docs.forEach(item=>{
      setEvents([...events,item.data()])
      console.log(item.data()); // Here shows all the items that stored in my firebase collection
     })
    }
    
    useEffect(()=>
    {
      fetchGames()
    }, [])
return(
<div>
{
     events.map((event)=>
        (
          <div>
            {event.home_color}
          </div>

        )
        )
    }
</div>
)

Eventually the events state will display only one item , unlike in the console log which displayed all the items , how to fix this?

drop down values are not reflecting until we remove focus from drop down after selection

here getDAtes and isChecked are boolean values and we fetch startDate from grid and caluclate starttime according to it. there are time values in allTimes array

//index.js

{field: 'starttime', headername: 'starttime', renderCell: (params) => (
  <Dropdown value={(getDates && isChecked) ? getStartTime(params.row.startDate) : 
   getDropDownStartTime(params)}
     options={[...allTimes]}
     onChange={(event) => {
       params.row[STARTTIME] = event.target.value;
       handleGridUpdate(params.row, STARTTIME);
     }}
  />
}

//handlegridupdate

handleGridUpdate = useCallback((row,type) => {
  const item = info[row.id] ? Object.assign({}, info[row.id]) : {};
  if(type === STARTTIME){
    item.starttime = row.starttime;
  }
info[row.id]=item;
dispatch(setInfo(info));
}, [dispatch, info]);

Angular ng303 problem but i cant do anything about that

this is my html

  <div class="mb-3">
    <label for="filterText" class="form-label">Ürün ara</label>
    <input type="text"   class="form-control" id="filterText" 
    placeholder="arama ifadesi giriniz">
  </div>
 
  
  <h4 style="text-align: left">Müşteriler</h4>
  <table class="table">
    <thead class="table-light">
      <tr>
        <td scope="col">Id</td>
        <td scope="col">İsim</td>
        <td scope="col">Email</td>
        <td scope="col">Soyisim</td>
       
    </thead>
    <tbody>
      <tr *ngFor="let users of users">
          <td>{{users.Id}}</td>
      </tr>
  </tbody>
  
  

this is my .ts

import { Component, OnInit } from "@angular/core";
 import { Users } from "src/app/models/Users";
import { AuthService } from "src/app/services/auth.service";
 

 

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
  user: Users   ;
  users : Users[] = []
  dataLoaded = false;
  filterText="";

  constructor(private authservice: AuthService
   ) {}

    ngOnInit(): void {
  this.getusers()
  }


  getusers() {
    this.authservice.getusers().subscribe(response=>{
      this.user = response.data
      console.log(this.users)
      this.dataLoaded = true;
    })   
  }

  getById(Id:number) {
    this.authservice.getById(Id).subscribe(response=>{
      this.user= response.data
      this.dataLoaded = true;
    })   
  }
  
  
 






}

this is error when i start the browser i see what should i do

NG0303: Can’t bind to ‘ngForOf’ since it isn’t a known property of ‘tr’. core.mjs:10178
Angular 3
UsersComponent_Template users.component.html:21
Angular 22
RxJS 6
Angular 8
emit
checkStable
onHasTask
hasTask
_updateTaskCount
_updateTaskCount
runTask
drainMicroTaskQueue

idea for designing a maze pattern

I’m in the process of writing path finding for Maze. I got this image while googling, which seems perfect for maze background. Any suggestions, How can I design this image using HTML, CSS and javascript.

should i use flex or grid or a simple table will do?

enter image description here

Attribute name to variavel javascript

I’m developing a dynamic page with javascript.

I’m not that advanced with the language, I’m trying to collect the name of the classes defined in the div through the html object variable,

so far I created a loop to repeat the structure created dynamically, assign a class: object to define as a class name for each block created through the objects variable

however I would like to use the name of each class summarized as a variable or if there is a way in which I could simply call the block and dynamically create html structure within it without the others clone the same.

// objs 
const html = [
    {
        id: 0,
        class: 'hero',
        titulo: "Teste",
    },
    {
        id: 1,
        class: 'section_1',
        titulo: "Teste 2",
    },
];

// main code
let section = document.createElement("section");
let el_page = document.getElementById("main");

const global = app => {

    const main = document.getElementById("main");
    const div = document.createElement("div");

    // get names and set div all class name
    for (let i = 0; i < html.length; i++) {
        div.setAttribute("class", app.class);
    }
    //creat el div
    main.append(div);
}

html.forEach(app => global(app));
    <main id="main">
teste
    </main>

Center columns with xAxis categories in highcharts

I intend to center the columns with the x-axis values ​​in the highcharts charts.

I have the following code:

Highcharts.chart('container', {
      chart: {
        type: 'column',
        options3d: {
          enabled: true,
          alpha: 0,
          beta: 0,
          viewDistance: 50,
          depth: 100
        }
      },

      title: {
        text: ''
      },

      xAxis: {
        type: 'category',
        labels: {
          skew3d: true,
          align: 'center',
          style: {
            fontSize: '16px'
          }
        }
      },

      yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
          text: 'Total de Denúncias',
          skew3d: true,
          align: 'center',
          style: {
            fontSize: '16px'
          }
        }
      },

      plotOptions: {
        column: {
          stacking: 'normal',
          depth: 200,
        }
      },

      series: series
    });

The graph looks like this:

enter image description here

As I show in the image the dates of the x axis are misaligned with the columns generated in the series. Can they help to center with each other?

AWS SSM getparameters make behavior node js sync

Is there any way to make AWS SSM getparameters sync?
Requirement :
The secret key, id stored in the SSM store should be accessible on the server up.
Using Node and express in the backend as a reverse proxy, so we have a constant.js file, it stores all the API URLs, paths, etc.

constats.js file

const api1url = 'http://example.com/path1'
const api1_secretkey = 'secret_key'
..................

module.export = {api1url,api1_secretkey}

So we wanted to call the ssm stuff in here before setting the const variables

const SSM = require('aws-sdk/clients/ssm');
const ssm = new SSM();
const params = {
   Names: ['/secret_key_api_1', '/secret_key_api_2'],
   WithDecryption: true,
   };
 const parameterList = await ssm.getParameters(params).promise();

I understand that await cant be without async, I just wanted to convey what I am expecting, without it being an async call or whether it be in the callback of getparameters.

const api1url = 'http://example.com/path1'
const api1_secretkey = parameterList.Parameter[1].Value

But since it is an async call we are not able to wait for it ,tried doing it in a separate async function and then returning the data but since the function is still async having difficulties.

custom hook not returning the dimensions of DOM element through ref parameters

I’m trying to create a custom hook that calculates the width and height of a given DOM element through useRef.

It calculates the dimensions however I’m not seeing any dynamic output. Meaning that as I resize the window, current width and height of the DOM element are not being updated. I need to toggle a css class based on the DOM element’s width.

This is my custom hook, which takes a ref as its sole parameter:

  useDimensionObserver = refParam => {

    if (refParam === null) return false;

    const getDimensionsFromRef = refParam => ({ width: refParam.current?.getBoundingClientRect().width, height: refParam.current?.getBoundingClientRect().height }),
      [dimensions, setDimensions] = React.useState(getDimensionsFromRef(refParam));


    React.useEffect(() => {
      const handleResize = () => setDimensions(getDimensionsFromRef(refParam));
      window.addEventListener("resize", handleResize);
      return () => window.removeEventListener("resize", handleResize);
    }, []);

    return refParam ? dimensions : null;

  },

This is the component in which I make use of useDimensionObserver:

 GeneralTotals = (props = IGeneralTotals) => {


    const containerRef = React.useRef(null),
      d = useDimensionObserver(containerRef);

    console.log(d); // As I resize the window, the container is also being resized so d.width and d.height need to be made dynamic.


    //I shall take action with 'd' potentially something like this...
    //if(d !== null && d.width < 450) setToggleInvisibleClass(true)

    return (<div className="card-title-tags" key="cal" ref={containerRef}>
      .....
    </div>);
  };

How to fix syntax error . i have run this below script find next roll output…but it is showing syntax error [closed]

const = require(“crypto”);

const roundSeed = “”; /YOUR SERVER SEED/

const clientSeed = “”; /YOUR CLIENT SEED/

const nonce = “”; /YOUR GAME’S NONCE/

function saltWithClientSeed(serverSeed, clientSeed) {

return crypto

.createHmac(“sha512”, serverSeed)

.update(clientSeed)

.digest(“hex”);

}

function generateHash(serverSeed) {

return crypto

.createHash(“sha256”)

.update(serverSeed)

.digest(“hex”);

}

function buildFinalHash(serverSeed, clientSeed, nonce) {

const noncedSeed = ${clientSeed} - ${nonce};

return saltWithClientSeed(serverSeed, noncedSeed);

}

function rollNumber(hash) {

let index = 0;

let lucky = parseInt(hash.substring(index * 5, index * 5 + 5), 16);

// keep grabbing characters from the hash while greater than

while (lucky >= Math.pow(10, 6)) {

index++;

lucky = parseInt(hash.substring(index * 5, index * 5 + 5), 16);

// if we reach the end of the hash, just default to highest number

if (index * 5 + 5 > 128) {

lucky = 9999;

break;

}

}

lucky %= Math.pow(10, 4);

lucky /= Math.pow(10, 2);

return lucky;

}

function verifyRoll() {

const hash = buildFinalHash(roundSeed, clientSeed, nonce);

return rollNumber(hash);

}

console.log(verifyRoll());

 

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.