read all the file and store in object format in node js / javascript

I wrote a code which help me to read all the folder file and make me store them in array format so my code looks like this

readAll.js

module.exports = readAllFile = () => {
  const arr = [];
  fs.readdir(path.join("./admin/requiredFiles"), (err, fileNames) => {
    if (err) throw console.log(err.message);
    // Loop fileNames array
    fileNames.forEach((filename) => {
      // Read file content
      fs.readFile(
        path.join("./admin/requiredFiles", `./${filename}`),
        (err, data) => {
          if (err) throw console.log(err.message);
          // Log file content
          arr.push(JSON.parse(data));
          fs.writeFileSync(
            path.join("./admin/execuetedFile", `config.json`),
            `${JSON.stringify(arr)}`,
            (err) => {
              if (err) throw console.log(err.message);
            }
          );
        }
      );
    });
  });
};

so this help me to read all the file which is present in admin/requiredFiles and let me save those file in executedFile

but the problem is this help me to store in array format but I want to store data in object form

suppose this is my few file data

file1.json

{
  "admin":{
    "right":"yes",
    "permission":"available"
  },
  "admin_power":{
    "addUser":"available",
    "deleteUser":"available"
  }
}

file2.json

{
  "directory":{
    "right":"yes",
    "permission":"modified"
  },
  "directory_power":{
    "add_directory":"yes",
    "assign_directory":"yes"
  }
}

so this are my some sample file and it help me to save them in format

config.json

[
 {
   "admin":{
     "right":"yes",
     "permission":"available"
   },
   "admin_power":{
     "addUser":"available",
     "deleteUser":"available"
   }
 },
 {
   "directory":{
     "right":"yes",
     "permission":"modified"
   },
   "directory_power":{
     "add_directory":"yes",
     "assign_directory":"yes"
   }
 }
]

and I don’t want this in this array form I want this copied files look like this

expectation config.json

{
   "admin":{
     "right":"yes",
     "permission":"available"
   },
   "admin_power":{
     "addUser":"available",
     "deleteUser":"available"
   },
   "directory":{
     "right":"yes",
     "permission":"modified"
   },
   "directory_power":{
     "add_directory":"yes",
     "assign_directory":"yes"
   }
 }

I just wanted to know what changes should I do so I can get output in my expectation format in config,json

how can I do to return an array with the positionId property of each of the positions [duplicate]

how can I return an array of “`positionId, so that I get the positionId“ of each of the positions.

that is, the expected return looks something like this:[2, 3], which is the “`positionId“ of each of the positions.

I tried doing it with forEach, but to no avail.

the object is in the following image

https://prnt.sc/tejeFHCZw2I3

my object:

const test = [
  {
    0: {
      colPos: 0,
      value: "valueX1",
      positionId: 2,
    },
  },
  {
    0: {
      colPos: 0,
      value: "valueY0",
      positionId: 3,
    },
  },
];

Property Undefined After Setting in Promise [duplicate]

I’m chaining two fetch calls to fetch restaurant information. I’m using the restaurant’s id to fetch the image url from the second fetch.

During the second fetch I’m setting the restaurant’s img property with the url returned.

When I go to use this data and console log the restaurant I can see the img property with the value. BUT when I console log restaurant.img it’s undefined. What am I missing here?

This is just with pure JS and using HTML elements on the DOM.

async function fetchImages(places) {
    return places.map((place) => {
        fetch(`https://byteboard.dev/api/data/img/${place.id}`)
            .then((res) => res.json())
            .then((image) => {
                place.img = image.img;
            });
        return place;
    });
}


async function loadPlacesWithImages() {
    const placeData = await fetch('https://byteboard.dev/api/data/places').then((res) => res.json());
    const placesWithImages = await fetchImages(placeData.places);

    return placesWithImages;
}

TypeError: str.charAt is not a function: at parse (/app/node_modules/pg-connection-string/index.js:13:11) Heroku Addons postgresql

when I run deploy my app to heroku I got this error

2022-05-26T01:38:34.587567+00:00 app[web.1]: TypeError: str.charAt is not a function
2022-05-26T01:38:34.587577+00:00 app[web.1]: at parse (/app/node_modules/pg-connection-string/index.js:13:11)
2022-05-26T01:38:34.587577+00:00 app[web.1]: at new ConnectionParameters (/app/node_modules/pg/lib/connection-parameters.js:56:42)
2022-05-26T01:38:34.587578+00:00 app[web.1]: at new Client (/app/node_modules/pg/lib/client.js:19:33)
2022-05-26T01:38:34.587579+00:00 app[web.1]: at BoundPool.newClient (/app/node_modules/pg-pool/index.js:213:20)
2022-05-26T01:38:34.587579+00:00 app[web.1]: at BoundPool.connect (/app/node_modules/pg-pool/index.js:207:10)
2022-05-26T01:38:34.587579+00:00 app[web.1]: at BoundPool.query (/app/node_modules/pg-pool/index.js:389:10)
2022-05-26T01:38:34.587580+00:00 app[web.1]: at Object.exports.getUserByEmail (/app/server/db/postgresql/queries.js:57:6)
2022-05-26T01:38:34.587580+00:00 app[web.1]: at /app/server/routes/api/user.js:32:38
2022-05-26T01:38:34.587580+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2022-05-26T01:38:34.587581+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/route.js:144:13)

although it is works fine on my localhost and heroku local.

exports.getUserByEmail = async (email) => {
  let user = "";
  await pool
    .query("SELECT email FROM users WHERE email = $1", [email])
    .then((res) => {
      if (res.rows[0]) {
        user = res.rows[0].email;
      }
    })
    .catch((e) => {
      throw e;
    });

  return user;
};
user.js

 try {
        let payload = {};
        const user = await poolQuery.getUserByEmail(email);
        if (user) {
          return res
            .status(400)
            .json({ errors: [{ msg: "User already exists" }] });
        } else {
          const salt = await bcrypt.genSalt(10);
          const encryptedPassword = await bcrypt.hash(password, salt);

Thank you a lot for your help.

Connect the dot vertically instead of horizontally on Line Chart

I have a line chart which shows multiple lines. X-axis represents date and Y-axis represents numeric reading. The lines represent the category PZ-1, PZ-2 & PZ-3. I have managed to remove the horizontal line that connect between the dots but now I want to connect the dots vertically that aligns based on the date on X-axis. I do not want to rotate the line or swap X-axis position with Y-axis and vice versa. Does anyone know how I can achieve the vertical line? Thank you

Below is my current code:

    const data = {
      datasets: [
        {label: 'PZ-1',data:[{x:'2022-02-25', y:40.551},{x:'2022-03-01', y:35.889},{x:'2022-03-02', y:34.68},{x:'2022-03-03', y:33.182},{x:'2022-03-04', y:30.82},{x:'2022-03-05', y:29.864},{x:'2022-03-08', y:28.413},{x:'2022-03-10', y:28.413},{x:'2022-03-12', y:28.424},{x:'2022-03-15', y:25.578},{x:'2022-03-17', y:27.07},{x:'2022-03-19', y:27.42},{x:'2022-03-22', y:27.478},{x:'2022-03-24', y:22.817},{x:'2022-03-26', y:22.576},{x:'2022-03-29', y:22.326},{x:'2022-03-31', y:22.011},{x:'2022-04-02', y:21.672},{x:'2022-04-05', y:21.561},{x:'2022-04-07', y:21.307},{x:'2022-04-09', y:34.988},{x:'2022-04-12', y:28.89},{x:'2022-04-14', y:28.618},{x:'2022-04-17', y:28.862},{x:'2022-04-19', y:27.727},{x:'2022-04-21', y:27.493},{x:'2022-04-23', y:27.149},{x:'2022-04-26', y:25.862},{x:'2022-04-28', y:25.59},{x:'2022-04-30', y:25.37},{x:'2022-05-04', y:24.79},{x:'2022-05-06', y:24.927}],backgroundColor: '#778899',borderColor: '#778899',borderWidth: 1,showLine: false},{label: 'PZ-2',data:[{x:'2022-02-22', y:40.994},{x:'2022-03-01', y:55.537},{x:'2022-03-02', y:62.907},{x:'2022-03-03', y:59.462},{x:'2022-03-04', y:55.175},{x:'2022-03-05', y:53.294},{x:'2022-03-08', y:50.284},{x:'2022-03-10', y:49.89},{x:'2022-03-12', y:50.334},{x:'2022-03-15', y:47.137},{x:'2022-03-17', y:48.726},{x:'2022-03-19', y:48.294},{x:'2022-03-22', y:48.002},{x:'2022-03-24', y:40.156},{x:'2022-03-26', y:39.857},{x:'2022-03-29', y:39.678},{x:'2022-03-31', y:39.331},{x:'2022-04-02', y:36.719},{x:'2022-04-05', y:36.438},{x:'2022-04-07', y:36.258},{x:'2022-04-09', y:72.891},{x:'2022-04-12', y:59.97},{x:'2022-04-14', y:59.578},{x:'2022-04-17', y:59.781},{x:'2022-04-19', y:60.408},{x:'2022-04-21', y:60.309},{x:'2022-04-23', y:59.82},{x:'2022-04-26', y:61.679},{x:'2022-04-28', y:61.539},{x:'2022-04-30', y:61.187},{x:'2022-05-04', y:59.871},{x:'2022-05-06', y:59.63}],backgroundColor: '#DB7093',borderColor: '#DB7093',borderWidth: 1,showLine: false},{label: 'PZ-3',data:[{x:'2022-02-22', y:51.455},{x:'2022-03-01', y:44.882},{x:'2022-03-02', y:58.791},{x:'2022-03-03', y:55.118},{x:'2022-03-04', y:48.364},{x:'2022-03-05', y:47.498},{x:'2022-03-08', y:45.477},{x:'2022-03-10', y:44.859},{x:'2022-03-12', y:45.468},{x:'2022-03-15', y:39.599},{x:'2022-03-17', y:40.561},{x:'2022-03-19', y:39.993},{x:'2022-03-22', y:40.232},{x:'2022-03-24', y:33.061},{x:'2022-03-26', y:33.169},{x:'2022-03-29', y:32.99},{x:'2022-03-31', y:32.849},{x:'2022-04-02', y:31.811},{x:'2022-04-05', y:31.412},{x:'2022-04-07', y:31.223},{x:'2022-04-09', y:84.506},{x:'2022-04-12', y:74.415},{x:'2022-04-14', y:74.079},{x:'2022-04-17', y:73.876},{x:'2022-04-19', y:87.873},{x:'2022-04-21', y:87.748},{x:'2022-04-23', y:87.45},{x:'2022-04-26', y:76.555},{x:'2022-04-28', y:76.401},{x:'2022-04-30', y:76.649},{x:'2022-05-04', y:75.585},{x:'2022-05-06', y:75.748}],backgroundColor: '#8B008B',borderColor: '#8B008B',borderWidth: 1,showLine: false}
    ]
    };
    // config 
    const config = {
      type: 'line',
      data,
      options: {
        layout: {
          padding: {
            left: 5
          }
        },
        indexAxis: 'x',
        scales: {
          y: {
            beginAtZero: true
          },
          x:{
            reverse: false,
            type: 'time',
            time: {
                  tooltipFormat: 'dd-MMM-yy',
                  displayFormats: {
                        day: 'dd-MMM-yy'
                    }
                },
            ticks: {
              source: 'date',
              autoSkip: false
            }
          }
        }
      }
    };
    // render init block
    const myChart = new Chart(
      document.getElementById('myChart'),
      config
    );
    * {
            margin: 0;
            padding: 0;
            font-family: sans-serif;
          }
          .chartCard {
            overflow:auto;
            background: rgba(255, 26, 104, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .chartBox {
            padding: 20px;        
            border-radius: 20px;
            border: solid 3px rgba(255, 26, 104, 1);
            background: white;
          }
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Line Chart</title>
  </head>
  <body>
    <div class="chartCard">
      <div class="chartBox">
        <canvas id="myChart" style="position: relative;height:1200px;width:1400px"></canvas>
      </div>
    </div>
    <script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
    </body>
    </html>

React Functional component with stateless class inside

I would like to ask or gather some important suggestions for this situation.

I wan’t to create my own Datetimepicker react component. I was searching some codes for easily constructing a calendar. Now I found some Regular Class which makes the calendar and I want to re-use it for creating my Datetimepicker component.

Now I would like to ask/open for suggestion for better or good practice that would be logical for my component.

In the code below, I have a functional component with a stateless class Day inside of it and I tried to instantiate it for future use. For me it works fine. Since I don’t want to look my code very messy or make it fewer lines, Is there anyway to separate this Day stateless class to import it in my Functional component? or any suggestions for this?. Or Can anyone explain to me if what am I doing is logically wrong or not, since I was using a Functional based component and putting a class inside of it. I would like to hear some good advice for this to implement in much better way.

import React, {useState} from "react";
import styles from "./Datetimepicker.module.scss";
import classNames from "classnames";
import CalendarSVG from "../../../styles/icons/Calendar/Calendar"

const Datetimepicker = (props) => {
  const {
    style,
    name,    
    color,
    size,    
    inputRef,
    errorMsg,
    helperMsg,
    placeholder,
    disabled,
    ...others
  } = props;

  
  const [addVisibility, setAddVisibility] = useState(false);

  const showCalendar = () => {
    setAddVisibility((prevState) => (!prevState));
  }

  const getWeekNumber = (date) => {
    const firstDayOfTheYear = new Date(date.getFullYear(), 0, 1);
    const pastDaysOfYear = (date - firstDayOfTheYear) / 86400000;
    
    return Math.ceil((pastDaysOfYear + firstDayOfTheYear.getDay() + 1) / 7)
  }

  class Day {
    constructor(date = null, lang = 'default') {
      date = date ?? new Date();    
      this.Date = date;
      this.date = date.getDate();
      this.day = date.toLocaleString(lang, { weekday: 'long'});
      this.dayNumber = date.getDay() + 1;
      this.dayShort = date.toLocaleString(lang, { weekday: 'short'});
      this.year = date.getFullYear();
      this.yearShort = date.toLocaleString(lang, { year: '2-digit'});
      this.month = date.toLocaleString(lang, { month: 'long'});
      this.monthShort = date.toLocaleString(lang, { month: 'short'});
      this.monthNumber = date.getMonth() + 1;
      this.timestamp = date.getTime();
      this.week = getWeekNumber(date);
    }
    
    get isToday() {
      return this.isEqualTo(new Date());
    }
    
    isEqualTo(date) {
      date = date instanceof Day ? date.Date : date;
      
      return date.getDate() === this.date &&
        date.getMonth() === this.monthNumber - 1 &&
        date.getFullYear() === this.year;
    }
    
    format(formatStr) {
      return formatStr
        .replace(/bYYYYb/, this.year)
        .replace(/bYYYb/, this.yearShort)
        .replace(/bWWb/, this.week.toString().padStart(2, '0'))
        .replace(/bWb/, this.week)
        .replace(/bDDDDb/, this.day)
        .replace(/bDDDb/, this.dayShort)
        .replace(/bDDb/, this.date.toString().padStart(2, '0'))
        .replace(/bDb/, this.date)
        .replace(/bMMMMb/, this.month)
        .replace(/bMMMb/, this.monthShort)
        .replace(/bMMb/, this.monthNumber.toString().padStart(2, '0'))
        .replace(/bMb/, this.monthNumber)
    }
  }

  const day = new Day();

  console.log('--day', day);

  return (
    <div className={styles.DatetimepickerWrapper}>
      <input
        className={classNames(
          styles.InputText,                
          errorMsg && styles.InputError,
          style ?? ""
        )}
        type="text"
        name={name}        
        placeholder={placeholder ?? "mm/dd/yyyy"}
        {...inputRef}
        {...others}
        disabled={disabled}        
      />
      <div className={addVisibility ? `${styles.CalendarVisible} ${styles.CalendarDropDown}` : `${styles.CalendarHidden}`}>
        <div className={styles.CalendarContainer}>
          <div className={styles.CalendarHeaderYear}>            
              <p>2022</p>            
          </div>
          <div className={styles.CalendarHeaderMonth}>
          <button type="button" className="prev-month" aria-label="previous month"></button>
            <h4 tabIndex="0" aria-label="current month">
              January
            </h4>
            <button type="button" className="prev-month" aria-label="next month"></button>
          </div>
          <div className={styles.CalendarDaysContainer}>
            <p>Test</p>
            <p>Test</p>
            <p>Test</p>
            <p>Test</p>
          </div>          
        </div>        
      </div>
      <CalendarSVG width={23} fill="#294197" className={styles.CalendarDateTimePickerIcon} onClick={() => showCalendar()}/>  
      {errorMsg && <span className={styles.ErrorMessage}>{errorMsg}</span>}
      {!errorMsg && helperMsg && (
        <span className={styles.HelperMessage}>{helperMsg}</span>
      )}
    </div>
  );
};

export default Datetimepicker;

Axios button not updating toggle button

I have a toggle button that changes isActive to true or false but it won’t change the button. I have to refresh the page to show the color change in the toggle button.
I’m new to vue.js. Please any advice? Thanks in advance!

async toggleNetworkGroup(audId, netId, turnOn)
        {

            let status = { isActive: turnOn };

            let url =  projConfig.apiRoot + `/s/groups/${audId}/network-groups/${netId}`;
            console.log(status);
            return axios.put(url, status)
                .then((res) =>
                {
                  
                    if(!this.isActive)
                    {
                        this.isActive = true;
                        
                        return { success: res };
                        
                    }
                    else if (this.isActive)
                    {
                        this.isActive = false;
                        return res;
                        
                    }
                    
                })
                .catch((error) =>
                {
                    console.log(error);
                    
                });
 <switcher
  :value="networkAudience.isActive"
  :disabled="loading"
  @input="(isChecked) => toggleNetworkGroup(isChecked, group.id, networkGroup.name, networkGroup.id)"
  />

enter image description here
enter image description here

Restructuring Object Hierarchy [closed]

Hello I’m trying to convert an initial object that i’m starting out with to the expected structured format. Any help is welcome, I know this will involve creating a recursive function. However, I’m a bit puzzled as to how to set it all up. Thank you in advance.

Initial

const x = {
 Id: { name: 'Id', fieldsByTypeName: {} },
 Subject: { name: 'Subject', fieldsByTypeName: {} },
 Profile: {
  Id: { name: 'Id', fieldsByTypeName: {} },
  Name: { name: 'Name', fieldsByTypeName: {} },
  CreatedBy: {
    name: 'CreatedBy',
    fieldsByTypeName: {
       CreatedBy: {
       Id: { name: 'Id', fieldsByTypeName: {} },
       Name: { name: 'Name', fieldsByTypeName: {} },
     }
    }
  },
  Record: {
     name: 'Record', 
     fieldsByTypeName: {
      Record: {
         Id: { name: 'Id', fieldsByTypeName: {} },
         Name: { name: 'name', fieldsByTypeName: {} },
      }
    }
  }
 }
}

Expected:

{
 Id: true,
 Subject: true,
 Profile: {
   Id: true,
   Name: true,
   CreatedBy: { 
      Id: true,
      Name: true
   },
   Record: {
    Id: true,
    Name: true
   }
 }
}

Most efficient way to remove objects from array based on key value objects in another array

Given the excludes and items arrays, I want to return an array of objects from items that don’t contain a key, value pair corresponding to a key, value pair object in excludes. Is there a better way of solving this other than using nested for loops?

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}];

const items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}];

//Expected output: [{color: "Blue", score: 100, age: 20}]

Combining result of two different Queries from two different Model MongoDB

So first I have a query that finds books that has been borrowed by user, it will search using the Borrow model

const bookqueryinitial = await Borrow.find({borrower_Id : String(_id), borrowStatus: req.query.status}).sort({"borrowDate": -1 }).skip(skip).limit(pageSize);

it will return results like this

[
   {
     _id: new ObjectId("628ebcc10944a1223397b057"),
     borrower_Id: '6278d1b6b4b7659470572e19',
     borrowedbook_Id: '62710ac63ad1bfc6d1703162',
     borrowStatus: 'pending',
     borrowDate: 2022-05-25T23:33:21.849Z,
     __v: 0
   },
   {
     _id: new ObjectId("628d9c0b9a3dc72f4aa72f1a"),
     borrower_Id: '6278d1b6b4b7659470572e19',
     borrowedbook_Id: '62710ac63ad1bfc6d170314d',
     borrowStatus: 'pending',
     borrowDate: 2022-05-25T03:01:31.416Z,
    __v: 0
    }
 ]

next is I will map through the borrowedbook_Ids of the result and store them in an array

const booksinsidequery = bookqueryinitial.map(bookids=>{
      return bookids.borrowedbook_Id
    })

then I will search the ids that is stored in array and search for those ids in the Book model

 const bookquery = await Book.find({ '_id': { $in: booksinsidequery } });

\and the result is somethign like this

 [
   {
    _id: new ObjectId("62710ac63ad1bfc6d170314d"),
     title: "Girl who kicked the Hornet's Nest",
     author: 'Larsson, Steig',
     genre: [ 'fiction' ],
     publisher: '',
     dateOfPublication: 2017-10-25T00:00:00.000Z,
     noOfCopies: 14,
     type: 'Article',
     form: 'Fiction',
     isbn: '978-69793-4824559-56755-9',
     dateAdded: 2003-04-23T00:00:00.000Z,
     noOfBookmarks: [ [Object] ],
     noOfLikes: [],

   },
   {
     _id: new ObjectId("62710ac63ad1bfc6d1703162"),
     title: 'We the Nation',
     author: 'Palkhivala',
     genre: [ 'philosophy' ],
     publisher: '',
     dateOfPublication: 2011-11-22T00:00:00.000Z,
     noOfCopies: 94,
     type: 'Book',
     form: 'Non-fiction',
     isbn: '978-65685-4156343-802140-8',
     dateAdded: 2010-06-08T00:00:00.000Z,
     noOfLikes: [],
     noOfBookmarks: []
   }
 ]

Now before sending the result of the query to the client side, I want to bind my initial queries from Borrow model to my Book model and the final result should be like this

 [
   {
    _id: new ObjectId("62710ac63ad1bfc6d170314d"),
     title: "Girl who kicked the Hornet's Nest",
     author: 'Larsson, Steig',
     genre: [ 'fiction' ],
     publisher: '',
     dateOfPublication: 2017-10-25T00:00:00.000Z,
     noOfCopies: 14,
     type: 'Article',
     form: 'Fiction',
     isbn: '978-69793-4824559-56755-9',
     dateAdded: 2003-04-23T00:00:00.000Z,
     noOfBookmarks: [ [Object] ],
     noOfLikes: [],

     //added properties based on matched condition  (Borrow.borrowedbook_Id === Book._id)
     borrowStatus: 'pending',
     borrowDate: 2022-05-25T03:01:31.416Z,
   },
   {
     _id: new ObjectId("62710ac63ad1bfc6d1703162"),
     title: 'We the Nation',
     author: 'Palkhivala',
     genre: [ 'philosophy' ],
     publisher: '',
     dateOfPublication: 2011-11-22T00:00:00.000Z,
     noOfCopies: 94,
     type: 'Book',
     form: 'Non-fiction',
     isbn: '978-65685-4156343-802140-8',
     dateAdded: 2010-06-08T00:00:00.000Z,
     noOfLikes: [],
     noOfBookmarks: [],
     
   //added properties based on matched condition  (Borrow.borrowedbook_Id === Book._id)
     borrowStatus: 'pending',
     borrowDate: 2022-05-25T23:33:21.849Z,
   }
 ]

How can I attain these results?

Not Able to Set Attribute of a Checkbox When It has Space in It’s Value Attribute

Having space between string in Value of a checkbox input like Item Two I am not able to set the checkbox to be checked.

<input type="checkbox" id="item2" name="check" value="Item Two">Item Two
$(":checkbox[value=Item Two]").prop('disabled', true);

Is there any way to fix this without changing the value of the input?

$(":checkbox[value=ItemOne]").prop("checked", "true");
$(":checkbox[value=Item Two]").prop('disabled', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="item1" name="check" value="ItemOne">Item One
<input type="checkbox" id="item2" name="check" value="Item Two">ItemTwo

React conditional rendering and return the value

Need a little guidance with conditional rendering in react


class Car extends React.Component {
id = '123456'

  render() {

   if("id".includes("1") === true){

    return <h2>$$${id}</h2>;

}
else{
         return <h2>{id}</h2>;
  }
}

For rendering $$$ for certain condition , apart from using if else and rendering
is there any way to conditionally render ???
a better way and the return can be quite long in big applications
is there a way to write conditional and return the value according to it?

handle unnamed JSONP in xmlHttpRequest Javascript [duplicate]

I have simple XMLHttpRequest.

  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);

  xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };

  xhr.send();

As you can see that I’m printing this.responseText in the console which outputs something like following

({ "status": "success", "data": { "title": "Post1" })

How can I get the JSON inside. I am totally aware of JSONP concepts but I don’t want $.ajax in jQuery, I’m trying to achieve this via javascript. Thanks

Display text value from Github Gist in Hugo site

I know I might be asking something quite simple but for the life of me I can’t seem to get my head around this and I’m definitely overseeing something simple but I don’t know what. Any help would be very appreciated.

I’m generating a static site using Hugo. On one of my pages, I want to create something like a progress bar, using a variable which I need to get from a file from a Github Gist.

Say this is the gist: https://gist.github.com/bogdanbacila/c5a9683089c74d613ad17cdedc08f56b#file-thesis-words-txt

The file only has one number, that’s it. What I’m asking is how to get that number from the gist and store it in hugo or at least just display it in some raw html. I want to mention that I’m not looking to use the provided embedded text, I’d rather just get the raw value. At the end of the day all I need is to read and display the number from the raw link here: https://gist.githubusercontent.com/bogdanbacila/c5a9683089c74d613ad17cdedc08f56b/raw/8380782afede80d234209293d4c5033a890e44b6/thesis-words.txt

I’ve asked this question on the Hugo forum and that wasn’t very helpful, instead of providing me with some guidance I got sent here. Here was my original question: https://discourse.gohugo.io/t/get-raw-content-from-github-gist-to-a-variable/38781

Any help would be greatly appreciated, I know there’s something very obvious which I’m not seeing, please guide me to the right direction, this doesn’t feel like it should be that complicated.

Best,
Bogdan