Problem, react-lazyload render all components at once

Hi I’m using Marvel API and I have this:

export default function App() {
  const [characters, setCharacters] = React.useState([]);
  
  const items = characters.map((character, idx) => (
    <LazyLoad key={idx} once throttle={2000} height={"300"}>
      <Character
        img={
          character.thumbnail.path +
          "/standard_xlarge." +
          character.thumbnail.extension
        }
        name={character.name}
      />
    </LazyLoad>
  ));

  React.useEffect(() => {
    fetch(
      "https://gateway.marvel.com/v1/public/characters?ts=1&apikey=e8aa37188987325dca0c570b01707e2c&hash=d784691874995aae3b9fb373b5a4d1da&limit=50"
    )
      .then((response) => response.json())
      .then((data) => setCharacters(data.data.results));
  }, []);

  React.useEffect(() => {
    forceCheck();
  });

  return (
    <div className="App">
      <h1>My Hero's</h1>
      <div>{characters.length ? items : null}</div>
    </div>
  );
}



function Character({ img, name }) {
  return (
    <div style={{ height: "300px", width: "200px", backgroundColor: "purple" }}>
      <h3>{name}</h3>
      <img height="200" width="200" src={img} />
    </div>
  );
}

My problem is that when the fetch loads all the data the lazyload components load all at once. Pls Help me. I’m using react-lazyload

My codesandbox

How to get the number of elements for elements that satisfy a condition

I’m having a problem. I have an array as shown below:

0: {type: 'Text', id_a: '123789', value: 'The fifth chapter of the World Première Ducati will be held at the Expo Dubai on December 9th.', number: 2, id: 7}
1: {type: 'Image', id_a: '123789', value: 'b_desertx-dwp2022-2-uc336332-high.jpg', number: 3, id: 8}
2: {type: 'Video youtube', id_a: '123789', value: 'https://youtu.be/SnuyDoXxC4g', number: 5, id: 10}
3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Of these I want, for example, to take those that have an id_a equal to 123456 and have me return the value (therefore, referring to id_a = 123456 it must return the two relative arrays) then

3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Except I get this below

{type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
{type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all her secrets with our video', number: 2, id: 2}

without the numbering in order to be able to retrieve the value (therefore using the value attribute) of each of them.

How can I do this?

   var myArr = JSON.parse(this.responseText);
   for(var i = 0, len = myArr.Items.length; i < len; i++){           
        var id_art = myArr.Items[i].id_a;
        if(id_art == 123456) {
            myArr.Items[i];
            console.log(myArr.Items[i]);
   }

How does one request additional scopes using google-auth-library with npm?

Our UI currently prompts the user to login with default scopes enabled.
In order to support a specific feature in our application, we’d like to request additional permissions only if they opt-in for the feature.

This link from Google explains how to do exactly that, but it uses their old javascript library that’s no longer supported.
How can I achieve the same thing with google-auth-library?

Implement a datePicker using javascript

I am trying to implement a date picker on a field , code is shown below but it does not work.

`
@Html.LabelFor(model => model.TimePeriod.EndDate, htmlAttributes: new { @class = “control-label col-md-8” })

@Html.EditorFor(model => model.TimePeriod.EndDate, new { htmlAttributes = new { @class = “datepicker form-control” } })
@Html.ValidationMessageFor(model => model.TimePeriod.EndDate, “”, new { @class = “text-danger” })

                <script type="text/javascript">
                    var currentTime = new Date()
                    var picker = new Pikaday(
                        {
                            field: document.getElementById('EndDate'),
                            firstDay: 1,
                            minDate: new Date('2010-01-01'),
                            maxDate: new Date('2033-12-12'),
                            yearRange: [2010, 2033],
                            numberOfMonths: 1,
                            theme: 'dark-theme'
                        });
                </script>
            </div>`

AntD+React: Browserslist config problem. I can’t customize the theme in Ant Design

I am trying to customize the theme in my very first draft of the AntD+React application. The steps I followed are from this official website. enter link description here

F:apppj1antd-demonode_modulesreact-scriptsscriptsstart.js:19


throw `enter code here`err;
  ^
Error [BrowserslistError]: Browserslist config should be a string or an array of strings with browser queries
    at check (F:apppj1antd-demonode_modulesbrowserslistnode.js:67:11)
    at parsePackage (F:apppj1antd-demonode_modulesbrowserslistnode.js:108:5)
    at F:apppj1antd-demonode_modulesbrowserslistnode.js:327:29
    at eachParent (F:apppj1antd-demonode_modulesbrowserslistnode.js:53:18)
    at Object.findConfig (F:apppj1antd-demonode_modulesbrowserslistnode.js:313:20)
    at Function.loadConfig (F:apppj1antd-demonode_modulesbrowserslistnode.js:232:37)
    at checkBrowsers (F:apppj1antd-demonode_modulesreact-dev-utilsbrowsersHelper.js:45:32)
    at Object.<anonymous> (F:apppj1antd-demonode_modulesreact-scriptsscriptsstart.js:78:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
  browserslist: true
}
error Command failed with exit code 1.

I don’t know how to deal with it. Can anyone help me out, please? Should I just simply change all the files below? If so, then how to change them.

Mongoose pre and post hooks do not work on models created with Model.discriminator

I am using mongoose 6.1.5.

I have a collection containing multiple types of related documents. Here is parameter-descriptor-item.model.js

const mongoose = require('mongoose');

const { Schema } = mongoose;

/** @summary The schema for a parameter item */
const itemSchema = new Schema({
  _id: String,
  name: Object,
});

itemSchema.pre(/^find/, function () {
  // eslint-disable-next-line no-console
  console.log('item pre hit');
});

/** @summary The base model for all parameter items */
module.exports = mongoose.model('Parameters', itemSchema);

ParameterDescriptor model inherits from ParameterDescriptorItem. Here is parameter-descriptor.model.js

const mongoose = require('mongoose');
const ParameterDescriptorItem = require('./parameter-descriptor-item.model');

const { Schema } = mongoose;

/** @summary The schema for additional fields for a project */
const parameterSchema = new Schema({
  direction: {
    type: String,
    enum: ['in', 'out'],
    required: true,
  },
  default: {
    type: Number,
    required: true,
  },
  min: {
    type: Number,
    required: false,
  },
  max: {
    type: Number,
    required: false,
  },
  unit: {
    type: String,
    required: false,
  },
});

parameterSchema.pre(/^find/, function () {
  // eslint-disable-next-line no-console
  console.log('parameter pre hit');
});


/** @summary The model for a parameter descriptor */
module.exports = ParameterDescriptorItem.discriminator('Parameter', parameterSchema);

And here is code to test the use of pre hooks.

const ParameterDescriptorItem = require('./parameter-descriptor-item.model');
const ParameterDescriptor = require('./parameter-descriptor.model');

await ParameterDescriptorItem.find();
// console shows: 'item pre hit'
await ParameterDescriptor.find();
// there is nothing additional in the console. Neither the 'pre' hooks from
// ParameterDescriptorItem or ParameterDescriptor is called.

This is a significant issue for me. Is there a way to address it? Is there a way to add pre and post hooks to models created with Model.discriminator?

ExpressJS: Best way to separate routes and accepting params?

I made a Express.js system where the files in the /routes folder are acting as a classic route (but with one file per route)

Example: /routes/get/user.js will be accessible with http://localhost:8080/user (the /get is to separate methods, it can be /post, /put…)

Here’s my entire index.js file: https://pastebin.com/ALtSeHXc

But actually, my problem is that I can’t pass params into the url like https://localhost:8080/user/random_id_here.

With this system, I think the best idea is to find a way to pass params on separated files too, but I don’t know how can it be done…

Here’s an example of one of my separated file:

module.exports = class NameAPI {
    constructor(client) {
        this.client = client
    }

    async run(req, res) {
        // Code here
    }
}

Maybe you’ll have a better system, or a solution for this. Thanks.

amazon-cognito-identity-js setupMFA problems

I am attempting to setup MFA for users after they reset their passcode. The code runs smoothly until I hit mfaSetup, specifically the line user.associateSoftwareToken(). When I pass in ‘this’ instead of user, I get the following error:

Uncaught (in promise) TypeError: callback is undefined

When I pass in user I get Uncaught (in promise) TypeError: callback.onFailure is not a function

I am truly at a loss of what to do and would appreciate any help.

Code below:


  const onSubmit = (event) => {
    event.preventDefault();

    const authDetails = new AuthenticationDetails({
      Username: email,
      Password: password
    });

    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    user.authenticateUser(authDetails, {
      onSuccess: (data) => {
        console.log('onSuccess:', data);
        if (location.pathname === '/') {
          // navigate('dashboard');
        }
      },
      onFailure: (err) => {
        console.error('onFailure:', err);
      },
      newPasswordRequired: (data) => {
        console.log(data);
        setNewPasscodeRequired(true);
      },
      mfaRequired: (data) => {
        console.log('mfa required');
      },
      mfaSetup: (challengeName, challengeParameters) => {
        console.log('in mfa setup');
        console.log(user.Session);
        user.associateSoftwareToken(user, {
          onFailure: (err) => {
            console.error('onFailure', err);
          },
          onSuccess: (result) => {
            console.log(result);
          }
        });
      },
      selectMFAType: (challengeName, challengeParameters) => {
        console.log(challengeName, challengeParameters);
        user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
      },
      totpRequired: (secretCode) => {
        console.log(secretCode);
        const challengeAnswer = prompt('Please input the TOTP code.', '');
        user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
      },
      associateSecretCode: (secretCode) => {
        const challengeAnswer = prompt('Please input the TOTP code.', '');
        user.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
      }
    });
  };

  const onSubmitPasscode = (event) => {
    event.preventDefault();

    if (passwordFirst !== passwordSecond) {
      alert('the two inputs provided are not the same');
    } else {
      const user = new CognitoUser({
        Username: email,
        Pool: UserPool
      });

      const authDetails = new AuthenticationDetails({
        Username: email,
        Password: password
      });

      user.authenticateUser(authDetails, {
        onFailure: (err) => {
          console.error('onFailure:', err);
        },
        onSuccess: (result) => {
          console.log(result);
        },
        newPasswordRequired: (userAttributes, requiredAttributes) => {
          console.log(userAttributes);
          console.log(requiredAttributes);
          delete userAttributes.email_verified;
          delete userAttributes.phone_number_verified;
          delete userAttributes.phone_number;
          console.log(userAttributes);
          user.completeNewPasswordChallenge(passwordFirst, userAttributes, {
            onFailure: (err) => {
              console.error('onFailure:', err);
            },
            onSuccess: (result) => {
              console.log('call result: ', result);
            },
            mfaSetup: (challengeName, challengeParameters) => {
              console.log('in mfa setup');
              console.log(user.Session);
              user.associateSoftwareToken(this, {
                onFailure: (err) => {
                  console.error('onFailure', err);
                },
                onSuccess: (result) => {
                  console.log(result);
                }
              });
            },
            selectMFAType: (challengeName, challengeParameters) => {
              console.log(challengeName, challengeParameters);
              user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
            },
            totpRequired: (secretCode) => {
              console.log(secretCode);
              const challengeAnswer = prompt('Please input the TOTP code.', '');
              user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
            },
            associateSecretCode: (secretCode) => {
              const challengeAnswer = prompt('Please input the TOTP code.', '');
              user.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
            }
          });
        }
      });
    }
  };

  const onMFASetup = () => {
    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    const authDetails = new AuthenticationDetails({
      Username: email,
      Password: passwordFirst
    });

    console.log(email);
    console.log(passwordFirst);

    user.authenticateUser(authDetails, {
      onFailure: (err) => {
        console.error('onFailure:', err);
      },
      onSuccess: (result) => {
        console.log(result);
      },
      mfaSetup: (challengeName, challengeParameters) => {
        user.associateSoftwareToken(this);
      },
      selectMFAType: (challengeName, challengeParameters) => {
        user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
      },
      totpRequired: (secretCode) => {
        const challengeAnswer = prompt('Please input the TOTP code.', '');
        user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
      },
      mfaRequired: (codeDeliveryDetails) => {
        const verificationCode = prompt('Please input verification code', '');
        user.sendMFACode(verificationCode, this);
      }
    });
  };

  const sendVerificationPin = (event) => {
    event.preventDefault();
    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    user.forgotPassword({
      onSuccess: (result) => {
        console.log('call result: ', result);
      },
      onFailure: (err) => {
        alert(err);
      }
    });
  };

  const onResetPassword = (event) => {
    event.preventDefault();

    console.log('in reset');

    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    console.log('user made');

    if (passwordFirst !== passwordSecond) {
      alert('the two inputs provided are not the same');
    } else {
      console.log('inputs are the same');
      user.confirmPassword(pin, passwordSecond, {
        onSuccess() {
          console.log('Password confirmed!');
          window.location.reload(true);
        },
        onFailure(err) {
          console.log('Password not confirmed!');
          console.log(err);
        }
      });
    }
  };

  return (
    <div>
      {!newPasscodeRequired && !forgotPassword && !setupMFA && (
        <div>
          <form onSubmit={onSubmit}>
            <input type="text" required value={email} onChange={(e) => setEmail(e.target.value)} />
            <input
              type="text"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <button type="submit">Login</button>
          </form>
          <button onClick={(e) => setForgotPassword(true)}>
            <Typography sx={{ paddingX: 5 }}>Forgot password?</Typography>
          </button>
        </div>
      )}
      {newPasscodeRequired && (
        <div>
          <form onSubmit={onSubmitPasscode}>
            <Typography>New Password</Typography>
            <input type="text" required onChange={(e) => setPasswordFirst(e.target.value)} />
            <Typography>New Password Again</Typography>
            <input type="text" required onChange={(e) => setPasswordSecond(e.target.value)} />
            <Typography>New Password Requirements</Typography>
            <Typography>
              At least 8 characters long, requiring upper and lower case letters, numbers, and
              special characters
            </Typography>
            <button type="submit">Submit new passcode</button>
          </form>
        </div>
      )}
      {forgotPassword && !newPasscodeRequired && (
        <div>
          <form onSubmit={sendVerificationPin}>
            <Typography>Please input the email for the account</Typography>
            <input type="text" required onChange={(e) => setEmail(e.target.value)} />
            <button type="submit">Send verification pin</button>
          </form>
          <form onSubmit={onResetPassword}>
            <Typography>Input the verification pin sent to your email below</Typography>
            <input type="text" required onChange={(e) => setPin(e.target.value)} />
            <Typography>New Password</Typography>
            <input type="text" required onChange={(e) => setPasswordFirst(e.target.value)} />
            <Typography>New Password Again</Typography>
            <input type="text" required onChange={(e) => setPasswordSecond(e.target.value)} />
            <Typography>New Password Requirements</Typography>
            <Typography>
              At least 8 characters long, requiring upper and lower case letters, numbers, and
              special characters
            </Typography>
            <button type="submit">Reset Password</button>
          </form>
        </div>
      )}
      {setupMFA && (
        <div>
          <div>SetupMFA</div>
          <button onClick={(e) => onMFASetup()}>Generate QR Code</button>
        </div>
      )}
    </div>
  );
};

How to get Vuex to add a urls from a Firebase getDownloadURL promise in Vue

I have an app that is using Firestore Storage JavaScript version 9, Vuex 4, and Vue 3. It needs to download image urls from Firestore Storage to display on an image tag.

My Firestore Storage is structured listings/${userID}/ with image files of that userID in it.

I have one component that needs image urls and is trying to get them from Firestore (line 35).

Listing.vue

<template>
  <div class="listing__container">
    <div class="listing__container_info">
      <h1 class="listing__header">{{ listing.title }}</h1>
      <p class="listing__paragraph">{{ listing.description }}</p>
      <div v-if="!isNaN(listing.stars)">
        <icon-star-line v-for="star in Number(listing.stars)" class="listing__icon" />
      </div>
    </div>
    <div class="listing__container_image">
      <img class="listing__image" :src="listingImageUrls[0]" alt="an image" />
    </div>
    <div class="listing__container_image">
      <img :src="listingImageUrls[1]" alt />
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  listing: Object,
})
import { computed, ref, toRefs } from 'vue'
import IconStarLine from '~icons/clarity/star-solid'
import { useStore } from 'vuex'

const store = useStore()
const { listing } = toRefs(props)

const userId = 'vlM46kRbhym3a3PW76t4'
store.dispatch('fetchUser', userId)
const user = computed(() => store.state.user)

store.dispatch('fetchListingImageUrls', user.value.id)
const listingImageUrls = computed(() => store.state.listingImageUrls)
</script>

<style lang="postcss">
.listing {
  @apply border-2 border-ui-100 rounded-3xl flex;
  &__header {
    @apply text-primary-900 text-3xl font-bold;
  }
  &__paragraph {
    @apply font-normal;
  }
  &__icon {
    @apply text-primary-500 inline;
  }
  &__container {
    @apply flex;
    &_info {
    }
    &_image {
      @apply w-52 h-36 overflow-hidden;
      .listing__image {
        /* @apply relative top-1/2 left-1/2; */
      }
    }
  }
}
</style>

I have another Vuex script that handles state and is calling getDownloadURL (line 57 to end of file)

store/index.js

import { createStore } from 'vuex'
import { initializeApp } from 'firebase/app'
import { getFirestore, collection, doc, addDoc, getDoc, getDocs, Timestamp } from 'firebase/firestore'
import { getStorage, ref, getDownloadURL, list } from 'firebase/storage'

const firebaseApp = initializeApp({
  apiKey: 'AIzaSyDANDyEb-LZn9OqcOECf93oLL48J1O2sWQ',
  authDomain: 'sploots-d050d.firebaseapp.com',
  projectId: 'sploots-d050d',
  storageBucket: 'sploots-d050d.appspot.com',
  messagingSenderId: '666246994336',
  appId: '1:666246994336:web:e6c1f5abd0467a63d22cc5',
  measurementId: 'G-173Y64V43X'
})

const db = getFirestore()
const storage = getStorage()

export const store = createStore({
  state: {
    user: {},
    listings: [],
    listingImageUrls: []
  },
  mutations: {
    addUser(state, user) {
      state.user = user
    },
    addListings(state, listings) {
      state.listings = listings
    },
    addListingImageUrls(state, urls) {
      state.listingImageUrls = urls
    }
  },
  actions: {
    async fetchUser({ commit }, userId) {
      const userRef = doc(db, `/users/${userId}`)
      const userSnap = await getDoc(userRef)
      commit('addUser', userSnap.data())
      if (!userSnap.exists()) {
        // doc.data() will be undefined in this case
        console.log("No such document!")
      }
    },
    async fetchListings({ commit }, userId) {
      const listingsRef = collection(db, `/users/${userId}/listings`)
      const listingsSnap = await getDocs(listingsRef)
      const listingsClean = []
      listingsSnap.forEach(doc => {
        let docClean = doc.data()
        listingsClean.push(docClean)
      })
      const listings = listingsClean
      commit('addListings', listings)
    },
    async fetchListingImageUrls({ commit }, userId) {
      const folderRef = await ref(storage, `listings/${userId}`)
      const imagesList = await list(folderRef)
      commit('addListingImageUrls', await getUrls(imagesList))
    },
  }
})

const getUrls = async (imagesList) => {
  const urls = imagesList.items.map(async imageRef => {
    const url = await getDownloadURL(imageRef)
    console.log(url)
    return url
  })
  return urls
}

And here is my package.json

{
  "name": "someApp",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "dependencies": {
    "firebase": "^9.4.1",
    "postcss-import": "^14.0.2",
    "vue": "^3.2.16",
    "vue-router": "^4.0.12",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@iconify-json/clarity": "^1.0.1",
    "@vitejs/plugin-vue": "^1.9.3",
    "autoprefixer": "^10.4.0",
    "eslint": "^8.2.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-vue": "^8.0.3",
    "postcss": "^8.4.4",
    "postcss-nested": "^5.0.6",
    "prettier": "^2.4.1",
    "tailwindcss": "^2.2.19",
    "unplugin-icons": "^0.12.23",
    "vite": "^2.6.4"
  }
}

Listing.vue is calling fetchListingImageURls on line 35 from store/index.js (line 57 and below) to get image urls from Firebase Storage. With this code the images don’t show. If I log listingImageUrls.value in listings.vue it is a proxy with a target that is an empty array. If I log urls from the store in getURLs it shows the urls as a fulfilled promise.

What is the issue here? I am pretty new to Vuex and Firestore so I think I am probably doing something wrong with one of those, or, as always, I am butchering something with my async calls.

Any help is appreciated 🙂

How to make a double await Node.js

Hi I can´t find a solution to my problem of functions in cascade,

Service A

print(await serviceB.methodA(myParameter));

Service B

async methodA(MyParameter){

            await methodB(MyParamter).then((value) =>{
                serviceA.methodC(value).then((result)=>{
                   console.log('result');
                   return result;
               });

            }
         );
         console.log('hi');
    }

So the output is

hi
undefined
result 

How I can wait to the second cascade of the then?? Because when getting undefined is broking my service A that must get “result”

Organize JSON data in HTML table with unique header rows for each data group

I have a JSON object that includes a key:value pair called callRoot. Example values for this key:value pair include @S, @C, and @W. There are multiple objects that have the same value and I hoping to set a HTML table head row at the start of each grouping and repeat it for each group of data.

Sample JSON data:

const commodities = [
  {
    actualSymbol: "@SF22",
    callRoot: "@S",
    open: 1.00,
    close: 2.00,
    userDescription: "SOYBEANS",
    // Other data
  },
  {
    actualSymbol: "@SH22",
    callRoot: "@S",
    open: 4.00,
    close: 6.00,
    userDescription: "SOYBEANS",
    // Other data
  },
  {
    actualSymbol: "@SK22",
    callRoot: "@S",
    open: 0.50,
    close: 2.30,
    userDescription: "SOYBEANS",
    // Other data
  },
  {
    actualSymbol: "@CH22",
    callRoot: "@C",
    open: 0.25,
    close: 0.75,
    userDescription: "CORN",
    // Other data
  },
  {
    actualSymbol: "@CK22",
    callRoot: "@C",
    open: 5.00,
    close: 6.75,
    userDescription: "CORN",
    // Other data
  },
  {
    actualSymbol: "@CN22",
    callRoot: "@C",
    open: 1.00,
    close: 2.00,
    userDescription: "CORN",
    // Other data
  },
  {
    actualSymbol: "@WH22",
    callRoot: "@W",
    open: 3.25,
    close: 2.00,
    userDescription: "WHEAT",
    // Other data
  },
  {
    actualSymbol: "@WK22",
    callRoot: "@W",
    open: 1.00,
    close: 2.00,
    userDescription: "WHEAT",
    // Other data
  },
  {
    actualSymbol: "@WN22",
    callRoot: "@W",
    open: 0.10,
    close: 0.20,
    userDescription: "WHEAT",
    // Other data
  }
];

Here is some of the code I have been playing with, though I could be way off on achieving my set requirements. A switch statement may be better suited than the if/else if statement

// Create empty arrays for each callRoot grouping
const soybeans = [];
const corn = [];
const wheat = [];

for(let commodity of commodities) {
  let callRoot = commodity.callRoot;
  if(callRoot.includes("@S")) {

  } else if(callRoot.includes("@C")) {

  } else if(callRoot.includes("@W")) {
  
  }
}

const soyHeader = soybean[0];
if(soyHeader) {
  // Render table header row HTML
}
// Render table row HTML

const cornHeader = corn[0];
if(cornHeader) {
  // Render table header row HTML
}
// Render table row HTML

const wheatHeader = wheat[0];
if(wheatHeader) {
  // Render table header row HTML
}
// Render table row HTML

Example HTML table structure:

<table>
  <tbody>
    <tr>
      <th colspan="9">SOYBEANS</th>
    </tr>
    <tr>
      <td>Month</td>
      <td>Last</td>
      <td>Change</td>
      <td>High</td>
      <td>Low</td>
    </tr>
    <tr>
      <td>August 2022</td>
      <td>1265'2</td>
      <td>-2'4</td>
      <td>1275'2</td>
      <td>1261'4</td>
    </tr>
    <tr>
      <td>August 2022</td>
      <td>1265'2</td>
      <td>-2'4</td>
      <td>1275'2</td>
      <td>1261'4</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <th colspan="9">CORN</th>
    </tr>
    <tr>
      <td>Month</td>
      <td>Last</td>
      <td>Change</td>
      <td>High</td>
      <td>Low</td>
    </tr>
    <tr>
      <td>August 2022</td>
      <td>1265'2</td>
      <td>-2'4</td>
      <td>1275'2</td>
      <td>1261'4</td>
    </tr>
    <tr>
      <td>August 2022</td>
      <td>1265'2</td>
      <td>-2'4</td>
      <td>1275'2</td>
      <td>1261'4</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <th colspan="9">WHEAT</th>
    </tr>
    <tr>
      <td>Month</td>
      <td>Last</td>
      <td>Change</td>
      <td>High</td>
      <td>Low</td>
    </tr>
    <tr>
      <td>August 2022</td>
      <td>1265'2</td>
      <td>-2'4</td>
      <td>1275'2</td>
      <td>1261'4</td>
    </tr>
    <tr>
      <td>August 2022</td>
      <td>1265'2</td>
      <td>-2'4</td>
      <td>1275'2</td>
      <td>1261'4</td>
    </tr>
  </tbody>
</table>

Rendered HTML table example

How to get property from TopoJSON file using D3.js version 7?

I have the following TopoJSON file:

{
    "type":"Topology",
    "arcs":[...],
    "transform":{
        "scale":[...],
        "translate":[...]
    },
    "objects":{
        "BRGR":{
            "type":"GeometryCollection",
            "geometries":[
                {
                "arcs":[[0,1,2]],
                "type":"Polygon",
                "properties":{
                    "codarea":"1"
                }
            },
            {
                "arcs":[[[3,4,5,-1]],[[6]]],
                "type":"MultiPolygon",
                "properties":{
                    "codarea":"2"
                }
            },
            {
                "arcs":[[[-5,7,8,9]],[[10]]],
                "type":"MultiPolygon",
                "properties":{
                    "codarea":"3"
                }
            },
            {
                "arcs":[[11,12,-9]],
                "type":"Polygon",
                "properties":{
                    "codarea":"4"
                }
            },
            {
                "arcs":[[-13,13,-2,-6,-10]],
                "type":"Polygon",
                "properties":{
                    "codarea":"5"
                }
            }]
        }
    }
}

I’m able to log it in the console using:

console.log(topology.objects.BRGR);

Having the following expected result:

{type: 'GeometryCollection', geometries: Array(5)}
  geometries: Array(5)
    0: {arcs: Array(1), type: 'Polygon', properties: {…}}
    1: {arcs: Array(2), type: 'MultiPolygon', properties: {…}}
    2: {arcs: Array(2), type: 'MultiPolygon', properties: {…}}
    3: {arcs: Array(1), type: 'Polygon', properties: {…}}
    4: {arcs: Array(1), type: 'Polygon', properties: {…}}
    length: 5
    [[Prototype]]: Array(0)
    type: "GeometryCollection"
    [[Prototype]]: Object

I’m unable to log the value of codarea directly. What brought me the closest solution was:

console.log(topojson.feature(topology, topology.objects.BRGR).features);

I’ve tried a lot of possibilities such as:

console.log(topojson.feature(topology, topology.objects.BRGR).features.properties.codarea);

without success. I have no idea what we have to do to get this value.
Actually I’d like to use it in a D3.js script to modify the color of the map on the fly.
The code is:

// svg general properties
var width = 1024,
    height = 512;

// set projection
// https://github.com/d3/d3-geo#projections
var projection = geo.geoCylindricalEqualArea() // projeção cilíndrica equivalente de Lambert
    .parallel(32)
    .scale(670)
    .rotate([45,14,0]);

// color scheme
var colorScheme = d3.schemeBlues[5];
colorScheme.unshift("#eeeeee")
var colorScale = d3.scaleThreshold()
    .domain([0, 1])
    .range(colorScheme);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var path = d3.geoPath()
    .projection(projection);

var g = svg.append("g");

// load and display the map
d3.json("map.json").then(function(topology) {

    g.selectAll("path")
        .data(topojson.feature(topology, topology.objects.BRGR).features)
        .enter().append("path")

//---->
//----> THIS IS WHERE CODAREA WOULD MODIFY COLOR
//---->
        .style("fill", function (event, d) {
            // pull data for this state
            d.codarea = ???;
            // set the color
            return colorScale(d.codarea);
        })

        .attr("d", path)
});

And the highlighted part I extracted from http://bl.ocks.org/palewire/d2906de347a160f38bc0b7ca57721328 but differently from the source I’m using D3 version 7

//----> MY CODE
//----> THIS IS WHERE CODAREA WOULD MODIFY COLOR
//---->
        .style("fill", function (event, d) {
            // pull data for this state
            d.codarea = ???;
            // set the color
            return colorScale(d.codarea);
        })

And here the original code:

   .attr("fill", function (d){
        // Pull data for this country
        d.total = data.get(d.id) || 0;
        // Set the color
        return colorScale(d.total);
    })

But as I said, I can’t get the proper data from my TopoJSON. How would this be possible, so I can use it in the script?

sumifs for matching data and week of month

I’m trying to create a spreadsheet that sums expenses and returns them based on week of month.

Table 1 has 4 columns (date, description, amount, sumbyweek_rows)
table 2 has multiple columns (key for “sumbyweek_rows,” summed amount from “amount,” and several cells that check data against “description” to know whether to sum it or not)

On table 2 I’m struggling with sumifs. I’d like my summed amount to sum if there is any cell with matching data from the amount cell on table 1, it uses the description cell as a key. But I’d like a second check to see if the date column is week 1, 2, 3, or 4 of month.

I can do it without the date by doing this:

SUM(ARRAYFORMULA(SUMIF(CurrentMonth!$BC$2:$BC$1000,
{C6:AC6},CurrentMonth!$BD$2:$BD$1000)))

But I’m stuck at trying to convert it to SUMIFS including date checks. I’ve tried testing 3 dating methods and none of them work, but I don’t see why:

SUMIFS(CurrentMonth!$BD$2:$BD$1000,CurrentMonth!$BA$2:$BA$1000,”>=””/01/“,CurrentMonth!$BA$2:$BA$1000,”<=””/07/“)

SUMIFS(CurrentMonth!$BD$2:$BD$1000,CurrentMonth!$BA$2:$BA$1000,”>=”&date(,,01),CurrentMonth!$BA$2:$BA$1000,”<=”&date(,,07))

SUMIFS(CurrentMonth!$BD$2:$BD$1000,1,WEEKNUM(BA2:BA1001)-WEEKNUM(EOMONTH(BA2:BA1001,-1)+1)