Loop through objects of objects in js

I have a data like this:

{
    "countries": {
        "US": {
            "details": {
                "code": 1,
                "population": ""
            },
            "people": [
                {
                    "name": ""
                },
                {
                    "name": ""
                }
            ]
        },
        "UK": {
            "details": {
                "code": 44,
                "population": ""
            },
            "people": [
                {
                    "name": ""
                },
                {
                    "name": ""
                }
            ]
        }
    }
}

I want to loop through it and extract people so I can loop through the people and display them on the site.

var countries = {
    "countries": {
        "US": {
            "details": {
                "code": 1,
                "population": ""
            },
            "people": [
                {
                    "name": ""
                },
                {
                    "name": ""
                }
            ]
        },
        "UK": {
            "details": {
                "code": 44,
                "population": ""
            },
            "people": [
                {
                    "name": ""
                },
                {
                    "name": ""
                }
            ]
        }
    }
}


for (let [key, value] of Object.entries(countries.countries)) {
    //console.log(value);
        for (var people in value.people) {
                    console.log(people);
        }
}

But I keep getting 0, 1, how can I get the value of people array?

How to use nodejs with ROS

I have a project where I have users on the backend and I have go-karts run by rosbag which in turn is on the frontend. I want to put my topics in a database but I have no idea what it could be, that’s when I found the rosnodejs option. Can anyone help me with how ROS works with nodejs? I can’t find one on the internet that is connected to port 9090, which works by default.

How show hide field in form based on dropdown selection With reactjs?

Hi I’m new with reactJs and I want to show a field after choosing one option of the dropdown list.
Actually I have a dropdown list contain “floor_no” values I want that when I choose “Ground Floor” to hide the field that contain the “stair Length” and when I choose the other options the field of “stair length” displayed.
this is my view code :

<Row>
          <Col sm='12' className='mb-1'>

            <Label className='form-label' for='name'>
              Floor Number <span className='text-danger'>*</span>
            </Label>
            <select id='floor_no' className='form-control' onChange={(e) => setFloorno(e.target.value)}>
             <option value='Ground Floor'> Ground Floor </option>
              <option value='Tirst floor'> First Floor </option>
              <option value='Second Floor'> Second Floor </option>
              <option value='Third Floor'> Third Floor </option>
              <option value='Fourth Floor'> Fourth Floor </option>
              <option value='Fifth Floor'> Fifth Floor </option>


            </select>
            <small className='text-danger'>{errorList.floor_no}</small>
            <br />
          </Col>

        </Row>
        
        <Row>
          <Col sm='12' className='mb-1'>
        


            <Label className='form-label' for='long_escalier'>
              Stair Length <span className='text-danger'>*</span>
            </Label>
            <input type='text' className="form-control"
              onChange={(e) =>
                setLongEscalier(e.target.value)
              }
              placeholder="Stair length" />
            <small className='text-danger'>{errorList.long_escalier}</small>
            <br/>
          </Col>
        </Row>
            
        

this is how I declared variables:

const [errorList, setError] = useState([]);
  const [floor_no, setFloorno] = useState("");
  const [long_escalier, setLongEscalier] = useState("");
  const [dispo_ascenseur, setAscenseur] = useState("");

thanks in advance

Why does my promise response show a the wrong format and not an object like I sent it as? [duplicate]

I have a fetch method:

fetch("http://localhost:3000/coin/" + String(TICKER_CODE))
.then((res) => {
    console.log(res.text());
}) .catch((err) => {
    /* handle errors */
    console.log("ERROR on fetch request", err)
});}

and my response.send

app.get('/coin/:coinID', (req, response) => {

sends this format:

var data_to_save = {
"name" : null,
"ticker": null,
"max_supply": null,
"circulating_supply": null,
"description": null,
"price": null,
"cmc_rank": null,
"percent_change_1h": null,
"percent_change_24h": null,
"percent_change_7d": null,
"percent_change_30d": null}

but for some reason, I get this when I console.log my res?

Response {type: 'cors', url: 'http://localhost:3000/coin/BTC', redirected: false, status: 200, ok: true, …}

and this when I console.log(res.text()) or res.json()

Promise {<pending>}
[[Prototype]]: 
Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: 42123.461982801804

I can’t seem to grasp what I’m doing wrong, I am currently sending the object as it is, and even tried to JSON.stringify it and send it over.

How can I reverse an array of object in Javascript?

I have an array written in this way:

[
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }
]

And I want to obtain an array writtenin this way:

[
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin' },
  { L: ['TestMetaCoin','Contract: MetaCoin'] },
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin'  },
  { L: ['TestMetaCoin','Contract: MetaCoin'] }
]

I tryed to use the nodejs function restore() but the result is:

[
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin' },
  { L: 'Contract: MetaCoin' },
  { L: 'TestMetaCoin', K: 'Contract: MetaCoin' },
  { L: 'Contract: MetaCoin' }
]

It completely overwrites the value in position 2 and 4, probably because it tries to create an existing key and therefore not being able to create it, accesses the old one by overwriting the value exists instead of creating an array with 2 values.
How can I get around this problem?
This is the code that I use:

var fristArray= [
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'K' },
  { TestMetaCoin: 'L', 'Contract: MetaCoin': 'L' }
]
var swapped=[]
for(var i=0;i<fristArray.length;i++) {
swapped.push(Object.fromEntries(Object.entries(fristArray[i]).map(([k, v]) => [v, k])))
}
console.log(swapped)

How to delete a property from a JavaScript object based on the type of the property?

I want to write a utility file which will be passed a js object with “n” properties. This utility file should delete all the properties from the object whose value is either an array or a nested object and then return it.

Ideally, it can also create a new object and include all properties from the passed object other than array values and nested objects.

I tried using destructing but didn’t find any way to delete properties based on type.

How can this be achieved ?

element.parentNode returns null while traversing through the DOM using JavaScript

I would like to traverse through the elements starting from Log in button up parent from parent up till I find an element with id, or I arrive to the top of the DOM.
https://profile.w3schools.com/signup?redirect_url=https://billing.w3schools.com/courses/html-video-course
I use the following code to create a CSS selector:

function getCssSelector(element) {
if (!(element instanceof Element)) {
    console.log("Element is not an Element: " + element)
    return;
}
var path = [];
while (element.nodeType === Node.ELEMENT_NODE) {
    var selector = element.nodeName.toLowerCase();
    if (element.id) {
        selector += '#' + element.id;
        path.unshift(selector);
        break;
    } else {
        var previousSibling = element, nth = 1;
        while (previousSibling = previousSibling.previousElementSibling) {
            if (previousSibling.nodeName.toLowerCase() == selector)
               nth++;
        }
        if (nth != 1)
            selector += ":nth-of-type("+nth+")";
    }
    path.unshift(selector);
    element = element.parentNode;

}
return path.join(" > ");

}

Whenever I arrive to the form element, the element.parentNode returns null. Looking at the DOM the element has a parent:

[![enter image description here][1]][1]

But in case I check the source code from the Chrome, I get the following:

<!doctype html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'none'; connect-src 'self' https://ekr.zdassets.com https://w3schools.zendesk.com https://*.w3schools.com https://*.google-analytics.com https://cognito-idp.us-east-1.amazonaws.com https://*.g.doubleclick.net https://*.google.com https://authapi.w3sdevelop.com https://authapi.w3stages.com https://authapi.w3spaces.com https://2k205wtqq3.execute-api.us-east-1.amazonaws.com https://aydmoags80.execute-api.us-east-1.amazonaws.com https://tryit-api.w3schools.com; script-src 'self' 'unsafe-inline' https://static.zdassets.com/ https://www.googletagmanager.com/ https://www.google-analytics.com/ https://www.google.com/recaptcha/ https://www.gstatic.com/; img-src 'self' https:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; base-uri 'self'; frame-src https://www.google.com/; ">
            <meta charset="utf-8">
                <link rel="icon" href="favicon.ico">
                    <meta name="viewport" content="width=device-width,initial-scale=1">
                        <meta name="theme-color" content="#000000">
                            <meta name="description" content="Profile pages">
                                <link rel="apple-touch-icon" href="logo192.png">
                                    <title>W3Schools</title>
                                    <script async="" nonce="f79c2bd4-92db-47cb-a921-fb3dd82e0188" src="https://www.googletagmanager.com/gtag/js?id=UA-3855518-1"/>
                                    <script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=41c2038e-584a-4eb0-b6fe-696d291af18b"/>
                                    <script src="datalayer.js"/>
                                    <link href="static/css/2.af63c107.chunk.css" rel="stylesheet">
                                        <link href="static/css/main.b5d8544f.chunk.css" rel="stylesheet"/>
                                        <body>
                                            <noscript>W3Schools Online Web Tutorials</noscript>
                                            <div id="root"/>
                                            <script type="text/javascript">window.zESettings={webWidget:{contactForm:{attachments:!0},color:{launcherText:"#FFFFFF"}}},zE("webWidget","setLocale","en")</script>
                                            <script src="static/js/runtime-main.f3c6b2f6.js"/>
                                            <script src="static/js/2.32a96327.chunk.js"/>
                                            <script src="static/js/main.b4c4cd86.chunk.js"/>
                                        </body>
                                    </html>

It looks like there is some problem with the HTML tags, but the page renders correctly and in dev tools under the elements tab I can see everything correctly.

I tried to look for the answer here on Stackowerflow, but I have not found anything. What can be the problem?
[1]: https://i.stack.imgur.com/ps3FK.png

Node.js basic error: Uncaught TypeError: Binance is not a function

newbie here! I’m trying to make a basic ping to the Binance crypto exchange using its exposed REST API and node.js. Instead of coding everything from 0, I’m planning to use a wrapper package in https://github.com/binance-exchange/binance-api-node that facilities interaction. I’ve downloaded the binance-api-node code from github into my node.js project.

After installing the package, when trying to run the included basic getting-started code to get the time from the server:

import Binance from 'binance-api-node';

const client = Binance();

client.time().then(time => console.log(time));

I’m getting this error:

Uncaught TypeError: Binance is not a function

I also tried:

const client = new Binance();

but I get another error saying Binance is not a constructor.

This is the function declaration in the index.d.ts of binance-api-node

    declare module 'binance-api-node' {
      export default function(options?: {
        apiKey?: string
        apiSecret?: string
        getTime?: () => number | Promise<number>
        httpBase?: string
        httpFutures?: string
        wsBase?: string
        wsFutures?: string
        proxy?: string
      }): Binance

...

Any help will be appreciated.

Thanks!

How to handle “accept cookies”?

I am trying to make a scraper that gets the reviews for hotel on tripadvisor.com. I was just working with pagination and testing if the browser would go all the way to the end, where there is no more pages.

Here is my code so far:

const puppeteer = require("puppeteer");
const cheerio = require("cheerio");

async function main() {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();

    await page.goto('https://www.tripadvisor.com/Hotels-g298656-Ankara-Hotels.html');

    while(true) {

        await page.click('a[class="nav next ui_button primary"]');
        await page.waitForNavigation({waitUntil: 'networkidle0'});

    } 

}

main();

However, this stops when the ‘accept cookies’ popup appears. How can I handle this?

Cannot retrieve text from xampp server because XMLHttprequest.readystate always returns ‘undefined’

I tried to access a .txt file stored in the htdocs folder of my xampp installation using only Javascript and no PHP. I only intend to use ajax to process a text file stored in server. This is my javascript code to make an asynchronous request:

(function(global){
    var ajaxUtils = {};
    function getRequestObject(){
        if(window.XMLHttpRequest){
            return (new XMLHttpRequest());
        }
        else{
            global.alert('Ajax is not supported!');
            return(null);
        }
    }

    ajaxUtils.sendGetRequest = function(requestUrl, responseHandler){
        var request = getRequestObject();
        request.onreadystatechange = function(){
            handleResponse(request, responseHandler);
        };
        request.open("GET",requestUrl,true);
        request.send(null);
    }

    function handleResponse(request, responseHandler){
        console.log(request.readystate + " " + request.status);
        if((request.readystate == 4) && (request.status == 200)){
            responseHandler(request);
        }
    }

    global.$ajaxUtils = ajaxUtils;
})(window);

This is how I passed parameters to ajaxUtils.sendGetRequest():

document.addEventListener("DOMContentLoaded", function(event){
    document.querySelector("button").addEventListener('click', function(){
        this.textContent='Said it!';
        $ajaxUtils.sendGetRequest('http://localhost/ajax/file.txt',function(request){
            var name = request.responseText;
            var message = "<h2>Hello " + name + '!</h2>';
            document.getElementById('content').innerHTML=message;
        });
    });
});

The code didn’t work and this is what I got in the console: request.readystate always returns ‘undefined’

‘readystate’ property of XMLHttprequest can have values 0,1,2,3, or 4, but here it always returns ‘undefined’. Does anybody know why this happened?

is this the right way to fetch data while usine usestate hooks? i use usestate hook but i don’t know if this the right way to fetch data

enter image description here

i just wrote the code and fetch usestate data like that cause I didn’t find some source to how doing it
in the form section I use onChange={event => setFirstName(event.target.value)} I don’t know where is the problem cause the data didn’t show up in the database

function OrderCP(props) {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [mobileNumber, setMobileNumber] = useState('');
  const [adress, setAddress] = useState('');
  const [city, setCity] = useState('');
  const [size, setSize] = useState('');
  const [quantity, setQuantity] = useState('1');






  function onOrderSubmit ()  {
  fetch('http://localhost:3000/orderCP', {
      method: 'post',
      mode: 'cors',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        firstname: setFirstName,
        lastname:setLastName,
        email: setEmail,
        mobilenumber: setMobileNumber,
        adress: setAddress,
        city: setCity,
        size:setSize,
        quantity: setQuantity

      })
    })
      .then(response => response.json())
      .then(user => {
        if (user.id) {
         return (
          this.props.loadUser(user),
         <Link to ='/orderCP/orderCompletedCP' /> )
        }
      })
  }

In Keystone js can withAuth have multiple listKeys?

Out of the box keystones auth is straight forward and nice and I want to continue using it, however I would like to set up different schema for the users of my front end than the standard Users schema used for the keystone app. I know i don’t need to and could just use the one table however the schemas are so different I’d like to know if I can for example keep using the authenticatedItem { ... on User {} } with my keystone and in my front end queries use something like authenticatedItem { ... on DifferentUser {} }.

Thanks