Reformat an array of JSON objects in JavaScript [closed]

I’m receiving the array of JSON objects pasted below from an API call, and would like to reformat it in javascript so that I have a new/simplified array of JSON objects that include:
the attributes in Object1 (just those from ID through City), and the attributes that are in the ‘parent’ object (attributes from q1_response through Notes). I expect I could do with a loop, but was hoping for something more efficient and straightforward.

[
    {
        "attributes": {
            "type": "Survey",
            "url": "/xxxx/data/xxxx/xxxx/xxxxx/axxxxxxxxxx"
        },
        "Object1": {
            "attributes": {
                "type": "Incident",
                "url": "/xxxx/data/xxxx/xxxx/xxxxx/bxxxxxxxxxx"
            },
            "Id": "aaabbb00001",
            "Survey_Version": "V2.0",
            "Incident_type": "Call",
            "CreatedDate": "2025-04-24",
            "Service_Responded": true,
            "City": "Houston"
        },
        "q1_response": "Example q1 response",
        "q2_response": false,
        "q3_response": false,
        "Notes": "Example notes"
    },
    {
        "attributes": {
            "type": "Survey",
            "url": "/xxxx/data/xxxx/xxxx/xxxxx/axxxxxxxxxx"
        },
        "Object1": {
            "attributes": {
                "type": "Incident",
                "url": "/xxxx/data/xxxx/xxxx/xxxxx/bxxxxxxxxxx"
            },
            "Id": "aaabbb00002",
            "Survey_Version": "V1.0",
            "Incident_type": "Call",
            "CreatedDate": "2025-04-26",
            "Service_Responded": true,
            "City": "Dallas"
        },
        "q1_response": "Example q1 response",
        "q2_response": true,
        "q3_response": false,
        "Notes": "Example notes"
    }
]

Desired outcome:

[
    {
        "Id": "aaabbb00001",
        "Survey_Version": "V2.0",
        "Incident_type": "Call",
        "CreatedDate": "2025-04-24",
        "Service_Responded": true,
        "City": "Houston",
        "q1_response": "Example q1 response",
        "q2_response": false,
        "q3_response": false,
        "Notes": "Example notes"
    },
    {
        "Id": "aaabbb00001",
        "Survey_Version": "V2.0",
        "Incident_type": "Call",
        "CreatedDate": "2025-04-24",
        "Service_Responded": true,
        "City": "Houston",
        "q1_response": "Example q1 response",
        "q2_response": false,
        "q3_response": false,
        "Notes": "Example notes"
    }
]

I tried various versions of filter and reduce, but didn’t get the desired result.

Firebase Auth working on web but not on mobile or simulator

I am using React Native and Expo to write a typescript app. I’m trying to add auth through firebase, but I am running into errors. Here is my firebaseConfig:

// firebaseConfig.ts
import { initializeApp } from 'firebase/app';
import { initializeAuth } from 'firebase/auth';

import { getFirestore } from 'firebase/firestore'; // if you're using Firestore

const firebaseConfig = {...};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = initializeAuth(app, {});

I have also tried importing @firebase/auth and I have tried using getAuth() to no avail.

I am able to login and create accounts successfully on web, but on mobile/mobile simulator, I keep getting the following error for multiple files:

 WARN  Route "./login.tsx" is missing the required default export. Ensure a React component is exported as default.
 ERROR  Error: Component auth has not been registered yet, js engine: hermes
 WARN  Route "./signup.tsx" is missing the required default export. Ensure a React component is exported as default.

My login.tsx has a default export:

import { useState } from 'react';
import { router } from 'expo-router';
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '@/firebaseConfig'; 
...

export default function LoginPage() { ...}

I am using the following dependencies:

  "dependencies": {
    "@expo/vector-icons": "^14.0.2",
    "@react-native-async-storage/async-storage": "^2.1.2",
    "@react-navigation/bottom-tabs": "^7.2.0",
    "@react-navigation/native": "^7.0.14",
    "date-fns": "^4.1.0",
    "expo": "^53.0.0",
    "expo-blur": "~14.1.4",
    "expo-constants": "~17.1.5",
    "expo-font": "~13.3.1",
    "expo-haptics": "~14.1.4",
    "expo-linking": "~7.1.4",
    "expo-router": "~5.0.5",
    "expo-splash-screen": "~0.30.8",
    "expo-status-bar": "~2.2.3",
    "expo-symbols": "~0.4.4",
    "expo-system-ui": "~5.0.7",
    "expo-web-browser": "~14.1.6",
    "firebase": "^11.7.3",
    "react": "19.0.0",
    "react-dom": "19.0.0",
    "react-native": "0.79.2",
    "react-native-gesture-handler": "~2.24.0",
    "react-native-reanimated": "~3.17.4",
    "react-native-safe-area-context": "5.4.0",
    "react-native-screens": "~4.10.0",
    "react-native-web": "^0.20.0",
    "react-native-webview": "13.13.5"
  },

ERR_UNSUPPORTED_DIR_IMPORT in webpack + typescript

I encountered error “ERR_UNSUPPORTED_DIR_IMPORT” when trying to call the script “webpack” in my project.
Thanks in advance to those who respond.

Used versions:
“webpack”: “^5.64.4”
“typescript”: “^4.9.5”
NodeJS: 23.7.0

Error text:

[webpack-cli] Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'C:Projectsproject-templatesJavaScriptwebpackwebpack-appwebpackConfig' is not supported resolving ES modules imported from C:Projectsproject-templatesJavaScriptwebpackwebpack-appwebpack.config.ts
    at finalizeResolution (node:internal/modules/esm/resolve:263:11)
    at moduleResolve (node:internal/modules/esm/resolve:860:10)
    at defaultResolve (node:internal/modules/esm/resolve:984:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:719:12)
    at #cachedDefaultResolve (node:internal/modules/esm/loader:643:25)
    at #resolveAndMaybeBlockOnLoaderThread (node:internal/modules/esm/loader:678:38)
    at ModuleLoader.resolveSync (node:internal/modules/esm/loader:701:52)
    at #cachedResolveSync (node:internal/modules/esm/loader:662:25)
    at ModuleLoader.getModuleJobForRequire (node:internal/modules/esm/loader:390:50)
    at new ModuleJobSync (node:internal/modules/esm/module_job:342:34) {
  code: 'ERR_UNSUPPORTED_DIR_IMPORT',
  url: 'file:///C:/Projects/project-templates/JavaScript/webpack/webpack-app/webpackConfig'
}
error Command failed with exit code 2.

webpack.config.ts file:

import { buildWebpack } from "./webpackConfig";

export const webpackConfig = (env, args) => {
    return buildWebpack(env, args);
}

./webpackConfig/index.ts file:

export * from "./webpackBuild";

I NEED directory imports and i tried this approaches:

  • Added “exports” in my package.json
        "exports": {
         "./*.ts": {
            "types": "./*.d.ts",
            "require": "./*.ts",
            "import": "./*.ts"
        }}
  • use index.ts file for export (above)
  • added Babel and babel.config.json file:
{
    "presets": ["@babel/preset-env"]
}

Not able to access environment variables (.env) in all the files. (node.js)

Everything works perfectly when I place the .env file in the root directory and call config() in the main.js. But the moment I move the .env file to the ./config directory, I have to call config({path: "config/.env"}) in every single file where I want to read environment variables from process.env.

Below are all my dependencies:

"dependencies": {
    "bcryptjs": "^3.0.2",
    "cookie-parser": "^1.4.7",
    "dotenv": "^16.5.0",
    "express": "^5.1.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.15.0"
  }
"devDependencies": {
    "@babel/preset-env": "^7.27.2",
    "concurrently": "^9.1.2",
    "morgan": "^1.10.0"
  }

Notes:

  1. I am using ES6 module.
  2. I have placed the import and function call on top before anything else, but still it’s not working.
  3. I have also placed import "dotenv/config" at the top.
  4. Node.js v22.12.0, npm v10.9.0.
  5. No errors in terminal.

Any help or tutorial/article link would be appreciated.

How to set result on a Promise outside of its constructor callback? [duplicate]

How do you resolve/reject a Promise outside of the constructor callback? My goal is to return a Promise that will later be resolved/rejected in the middle of a promise chain. E.g.,

function makeApiCall(form_data) {
    const out_promise = new Promise(); // Promise to return.
    // TypeError: Promise resolver undefined is not a function

    fetch(url, {body: form_data))
        .then(preprocessApiResponse)
        .then(async (response) => {
            out_promise.resolve(response); // Resolve created promise.
            //          ^ undefined
            return response;
        }, async (reason) => {
            out_promise.reject(reason); // Reject created promise.
            //          ^ undefined
            return error;
        })
        .finally(cleanupApiResponse);

    return out_promise;
}

response = await makeApiCall(form_data);

How to set result on a Promise outside of its constructor callback?

How do you resolve/reject a Promise outside of the constructor callback? My goal is to return a Promise that will later be resolved/rejected in the middle of a promise chain. E.g.,

function makeApiCall(form_data) {
    const out_promise = new Promise(); // Promise to return.
    // TypeError: Promise resolver undefined is not a function

    fetch(url, {body: form_data))
        .then(preprocessApiResponse)
        .then(async (response) => {
            out_promise.resolve(response); // Resolve created promise.
            //          ^ undefined
            return response;
        }, async (reason) => {
            out_promise.reject(reason); // Reject created promise.
            //          ^ undefined
            return error;
        })
        .finally(cleanupApiResponse);

    return out_promise;
}

response = await makeApiCall(form_data);

Unable to Overwrite File with Node fs

I am working on a TypeScript library generates API documentation (using jsdoc-to-markdown) and I am trying to do some post-processing of the files after they are all generated. Everything is working correctly except when I try to overwrite the file, the file is not updated. However, if I write the data to a new file, then I see my changes.

async function processFiles() {
  try {
    const codeElementPattern = /<code>(.+?)</code>/g;
    const codeElementNamePattern = />(.+?)</;

    let fileData = "";

    for (const [, { formattedPath }] of classFileMap) {
      fileData = await fs.promises.readFile(formattedPath, {encoding: "utf8", flags: fs.constants.O_RDWR});

      const matches = fileData.match(codeElementPattern);

      for (const match of matches) {
        const nameValue = match.match(codeElementNamePattern);
        const documentPath = classFileMap.get(nameValue[1]);

        if (documentPath === undefined || documentPath === null) {
          continue;
        }

        fileData = fileData.replace(
          match,
          `[${nameValue[1]}](${documentPath.relativePath})`,
        );
      }

      await fs.promises.writeFile(formattedPath + 'd', fileData); // <-- Writes changes correctly to new file
      await fs.promises.writeFile(formattedPath, fileData); //<-- Does not update existing file
    }
  } catch (err) {
    console.warn(`Unable to process file ${formattedPath} - Error:n${err}`);
  }
}

I have tried using the following options to overwrite the existing file, but none worked:

  • { encoding: "utf8", flags: fs.constants.O_TRUNC | fs.constants.O_WRONLY }
  • { encoding: "utf8", flags: fs.constants.O_TRUNC | fs.constants.O_RDWR }
  • { encoding: "utf8", flags: fs.constants.O_TRUNC }
  • { encoding: "utf8", flags: 'w'}

I have also tried it with no options (i.e., default options) from both the file write call as well as the read call, without success, and no exceptions are thrown which could help me figure out what is going wrong.

As the new file (the one with the d appended to the file name/path) has the correct data, this is an issue with the overwriting call.

How can I update the client with information about the state of the currently active form request in sveltekit?

I am making a web app which sends some requests to external APIs which can take some time to complete. The user types information in a form, which is received by a +page.server.ts file in the default form action. Once it is done processing the request, information is displayed to the user.

However, since this takes so long, I wanted to add some messages that I can send to the client to display while they wait to inform them of the status of their request.

Below is a pseudocode-style representation of the functionality I am looking for:

+page.server.js

export const actions = {
  default: async ({ request }) => {
    sendClientMessage("I'm processing your request!")

    await processSomething()
    sendClientMessage("Thing 1 done!")

    await processOtherThing()
    sendClientMessage("Thing 2 done!")
  }
}

+page.svelte

<script>
  onClientMessage((message) => {
    console.log(`Got message from server: ${message}`)
  }
</script>

I’ve seen people suggest using things like websockets and socket.io. This sounds sort of like what I want, but from what I’ve seen, these require some pretty complicated manual client management to avoid sending messages to every connected client. Is there any simple-ish library that achieves the results I want, or are these going to be my only options? I don’t really need two-way communication as the only details the user sends are in the initial request.

Perhaps more importantly, is all of this effort worth it for relatively little functionality?

If anyone has any ideas or advice, it would be greatly appreciated. 🙂

I can’t seem to get .waitForDisplayed/exists methods to work for elements the moment i switch between apps

const el = browser.$(‘//android.view.View[@content-desc=”Login”]’);
await el.waitForDisplayed({timeout:5000});

if this snippet gets executed without shifting between apps, it works like a charm but i can’t seem to get it working when i transition between chrome and the native app.

I’m changing the context as well and i’m making sure that the context is indeed changed before sending commands.
I’ve tried managing different sessions for each app but it messes with the global browser session as it performs DELETE on the original browser and fails the test on completion hooks.

This is what i get in the terminal.

INFO webdriver: DATA {
[0-0]   script: 'checkVisibility(...) [612 bytes]',
[0-0]   args: [
[0-0]     {
[0-0]       'element-6066-11e4-a52e-4f735466cecf': '00000000-0000-007f-0000-008f00000003',
[0-0]       ELEMENT: '00000000-0000-007f-0000-008f00000003'
[0-0]     },
[0-0]     {
[0-0]       withinViewport: false,
[0-0]       contentVisibilityAuto: true,
[0-0]       opacityProperty: true,
[0-0]       visibilityProperty: true
[0-0]     }
[0-0]   ]
[0-0] }
[0-0] 2025-05-23T14:57:44.794Z ERROR webdriver: WebDriverError: Method is not implemented when running "execute/sync" with method "POST" and args "function checkVisibility(elem, params) {
[0-0]       if (typeof elem.checkVisibility === "function") {
[0-0]         return elem.checkVisibility(params);
[0-0]       }
[0-0]       return null;
[0-0]     }"

Maintain Aspect Ratio with CSS instead of JavaScript [duplicate]

I’m currently using flex to layout a series of buttons in a wrapper container.

The regular buttons get their widths and heights based on the padding and the inner text, but the image button gets its height set to 100%.

The problem I’m having is that the only way I’ve been able to maintain the square aspect ratio of the image button is by setting its width to its height using JavaScript.

I was wondering if there is a way to do this with CSS instead.

JSFiddle : https://jsfiddle.net/2qdbvr93/

makeSquare(".image button");
window.addEventListener("resize", () => {
  makeSquare(".image button");
});

function makeSquare(selector) {
  const buttons = document.querySelectorAll(selector);
  buttons.forEach((button) => {
    button.style.width = `${button.offsetHeight}px`;
  });
}
.wrapper {
  display: flex;
  align-items: stretch;
}

.regular button {
  padding: 20px 40px;
  background-color: #aaaaaa;
}

.image button {
  height: 100%;
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT7vnGsgBgV8QW50dp-wZ4GoCNWu4egKYuxAw&s");
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}
<div class="wrapper">
  <div class="regular">
    <button>RegA</button>
  </div>

  <div class="image">
    <button></button>
  </div>

  <div class="regular">
    <button>RegB</button>
  </div>
</div>

UPDATE

I did try to get this working with css aspect-ratio, but didn’t have any success. I’m not sure it works with a dynamic height.

create and add multiple users to different shared Google drives

How to create and add multiple users to different shared Google drives in Google script according to the Department?.
A list of departments and user names and passwords will be issued on a separate Google sheet.
A list of groups and google drive’s ID will be issued on a separate Google sheet in the table.

I use this script but it works only to create users and add them to groups but not to drives.

function createUserAndAssignRoles() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet();
  const userSheet = sheet.getSheetByName("User Data");
  const configSheet = sheet.getSheetByName("Configuration");

  const users = userSheet.getDataRange().getValues();
  const configData = configSheet.getDataRange().getValues();

  const teamGroups = {};
  const teamDrives = {};
  const teamDriveRoles = {};
  const locationGroups = {};

  configData.forEach(row => {
    const type = row[0];
    const name = row[1];
    const groupEmails = row[2] ? row[2].split(',').map(e => e.trim()) : [];
    const driveId = row[3] || '';
    const driveRole = row[4] || '';

    if (type === 'Team') {
      if (!teamGroups[name]) teamGroups[name] = [];
      if (!teamDrives[name]) teamDrives[name] = [];
      if (!teamDriveRoles[name]) teamDriveRoles[name] = [];

      teamGroups[name] = teamGroups[name].concat(groupEmails);
      if (driveId) {
        teamDrives[name].push(driveId);
        teamDriveRoles[name].push(driveRole);  // can be empty string
      }
    } else if (type === 'Location') {
      if (!locationGroups[name]) locationGroups[name] = [];
      locationGroups[name] = locationGroups[name].concat(groupEmails);
    }
  });

  for (let i = 1; i < users.length; i++) {
    const row = users[i];
    const firstName = row[0];
    const lastName = row[1];
    const email = row[2];
    const password = row[3];
    const team = row[4];
    const location = row[5];

    createGoogleUser(email, firstName, lastName, password);

    if (team && teamGroups[team]) {
      teamGroups[team].forEach(groupEmail => {
        addUserToGroup(email, groupEmail);
      });
    }

    if (team && teamDrives[team] && teamDriveRoles[team]) {
      teamDrives[team].forEach((driveId, index) => {
        let role = teamDriveRoles[team][index] || 'reader';  // Default role
        addUserToDrive(email, driveId, role);
      });
    }

    if (location && locationGroups[location]) {
      locationGroups[location].forEach(groupEmail => {
        addUserToGroup(email, groupEmail);
      });
    }
  }
}

function createGoogleUser(email, firstName, lastName, password) {
  try {
    AdminDirectory.Users.insert({
      primaryEmail: email,
      name: { givenName: firstName, familyName: lastName },
      password: password,
      orgUnitPath: "/",  // Change if you use a custom OU
      changePasswordAtNextLogin: false
    });
    Logger.log('User created: ' + email);
  } catch (error) {
    Logger.log('Error creating user ' + email + ': ' + error.message);
  }
}

function addUserToGroup(email, groupEmail) {
  try {
    AdminDirectory.Members.insert({
      email: email,
      role: 'MEMBER'
    }, groupEmail);
    Logger.log('User added to group: ' + groupEmail);
  } catch (error) {
    Logger.log('Error adding user to group: ' + error.message);
  }
}

function addUserToDrive(email, driveId, role) {
  try {
    const validRoles = ['reader', 'writer', 'commenter', 'fileOrganizer', 'organizer'];

    role = role.trim().toLowerCase();
    if (role === 'viewer') role = 'reader';  // Normalize alias
    if (!validRoles.includes(role)) {
      Logger.log(`Invalid role "${role}" for drive ${driveId}. Defaulting to "reader".`);
      role = 'reader';
    }

    Drive.Permissions.insert({
      type: 'user',
      role: role,
      emailAddress: email
    }, driveId, {
      sendNotificationEmail: false,
      supportsAllDrives: true
    });

    Logger.log('User added to drive: ' + driveId + ' with role: ' + role);
  } catch (error) {
    Logger.log('Error adding user to drive: ' + error.message);
  }
}

how to get the newest variable when using react event bind

I am using this event bind to listening the window tab switch:

const handleVisibilityChange = () => {
    if (!wsSocketIOProvider) {
      console.warn("provider is null");
      return;
    }
    let connected = wsSocketIOProvider?.ws?.connected;
    if (connected) {
      console.log("connected is ok");
    } else {
      console.error("disconnected......");
      window.location.href = "/doc/tab";
    }
  };

  React.useEffect(() => {
    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, []);

now I facing when trigger the handleVisibilityChange, the variable wsSocketIOProvider always null even though the wsSocketIOProvider changed. why did this happen? What should I do to tracing the lastest variable of wsSocketIOProvider?

MapTiler SDK markers move across the map when scrolling

I’m trying to create markers using the MapTiler SDK. I have a map component that displays a MapTiler map, and in its TypeScript file, I’m adding markers like this:

 const marker = new maptilersdk.Marker({ anchor: 'bottom' })
            .setLngLat([105.8509611111111,21.03162777777778,])
            .addTo(this.map);
          console.log('Marker position:', marker.getLngLat());

The coordinates are pointing to Hanoi, and logging the marker’s coordinates shows the correct longitude and latitude. However, when zoomed out, the marker appears somewhere in the ocean. As I zoom in, the marker smoothly moves straight toward the intended position in Hanoi. When fully zoomed in, the marker reaches the correct location and stays there until I zoom out again.enter image description hereenter image description here

(intended)End location at max zoom:enter image description here

Markers are made after map has been loaded

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { Map, MapStyle, config } from '@maptiler/sdk';
import * as maptilersdk from '@maptiler/sdk';
import ExifReader from 'exifreader';

 ngAfterViewInit() {
    const initialState = { lng: 106.6000, lat: 17.4833, zoom: 5 };

    this.map = new Map({
      container: this.mapContainer.nativeElement,
      style: MapStyle.STREETS,
      center: [initialState.lng, initialState.lat],
      zoom: initialState.zoom
    });
    this.map.on('load', () => {
      const marker = new maptilersdk.Marker({ anchor: 'bottom' })
            .setLngLat([105.8509611111111,21.03162777777778,])
            .addTo(this.map!);
          console.log('Marker position:', marker.getLngLat());
    });
  }

Here are my .HTML and .scss if of any use. Thank you for any help!

<div class="map-wrap">
  <div #map class="map"></div>
</div>

<img id="img1" src="/IMG_1100.jpg" alt="Testbild" crossorigin="anonymous" />

.map-wrap {
  width: 100vw;      /* 100% der Viewport-Breite */
  height: 95vh;      /* 95% der Viewport-Höhe, z.B. fast voll */
  margin: 0 auto;    /* zentriert horizontal, meist redundant bei 100% Breite */
  border: 1px solid #000;
}

.map {
  width: 100%;
  height: 100%;
}

#img1 {
  display: none;
}

How to open dropdown menu from other class

I have something like this and i want to open menu using not only .dropdown-btn but also when somebody click ‘a’ class in menu. It is some easy way to change it ?

JS:

 //Submenu Dropdown Toggle
  if ($(".main-header li.menu-item-has-children ul").length) {
    $(".main-header .navigation li.menu-item-has-children > a").append(
      '<div class="dropdown-btn"><span class="fa fa-angle-right"></span></div>'
    );
  }

  //Mobile Nav Hide Show
  if ($(".side-menu__block").length) {
    var mobileMenuContent = $(".main-header .nav-outer .main-menu").html();
    var mobileNavContainer = $(".mobile-nav__container");
    mobileNavContainer.append(mobileMenuContent);

    //Dropdown Button
    mobileNavContainer
      .find("li.menu-item-has-children .dropdown-btn")
      .on("click", function (e) {
        e.preventDefault();
        $(this).toggleClass("open");
        $(this).parent("a").parent("li").children("ul").slideToggle(500);
      });
    
      
    //Menu Toggle Btn
    $(".mobile-nav-toggler").on("click", function () {
      $(".side-menu__block").addClass("active");
    });

    $(".side-menu__block-overlay,.side-menu__toggler, .scrollToLink > a ").on(
      "click",
      function (e) {
        $(".side-menu__block").removeClass("active");
        e.preventDefault();
      }
    );
  }

i try to change JS and still the same problem