How do I turn one object into multiple objects depending on how many keys there are? [duplicate]

I have a simple question.

I want to turn this array of one object

[
    {
        id: 1,
        caseId: "Default Case Set",
        casenbr: "CASEWORK",
        submitterCasenbr: 34,
        othref: 0,
        sta: 0,
        type: 0,
        create: 0,
        startd: 0
    }
]

into an array of multiple objects like this…

[
    {
        id: 1
    },
    {
        caseId: "Default Case Set"
    },
    {
        casenbr: "CASEWORK"
    },
    {
        submitterCasenbr: 34
    },
    {
        othref: 0
    },
    {
        sta: 0
    },
    {
        type: 0
    },
    {
        create: 0
    },
    {
        startd: 0
    }
]

What would be the best approach to do this? Basically, I want to take all the key/value pairs in the object and turn them each into objects.

So, if I have an array of one object with 100 key/value pairs, I’d want to create one array of 100 objects that have only one key/value pair.

The reason I’m doing this is to create an array that I can use for an ngFor directive in my Angular 13 app.

I don’t know if there is a way for ngFor in Angular to repeat over the key/value pairs of one object in one array, so that’s what I’m creating one array of multiple objects.

Passing page data in hidden field

I am trying to pass data through a form via the hidden field of a form. My question is, can I grab the date from that specific event page that gets displayed and pass it through into my custom field. What would be the best approach to grab that data already on that page? Since we have multiple events I want a singular form with the ability to grab the data already created by that specific event and use a singular form to pass the date field listed on that event page.

multi-line chart chart.js bootstrap

I have this code that currently shows one line on my chart:

    var myLineChart =  new Chart(ctx, {
  type: 'line',
  data: {
    // labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    labels: dateArray,
    datasets: [{
      label: "Weight",
      lineTension: 0.3,
      backgroundColor: "rgba(78, 115, 223, 0.5)",
      borderColor: "rgba(78, 115, 223, 1)",
      pointRadius: 3,
      pointBackgroundColor: "rgba(78, 115, 223, 1)",
      pointBorderColor: "rgba(78, 115, 223, 1)",
      pointHoverRadius: 3,
      pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
      pointHoverBorderColor: "rgba(78, 115, 223, 1)",
      pointHitRadius: 10,
      pointBorderWidth: 2,
      // data: theDataArray[i]
      data: theDataArray
    }],
  },
  options: {
    maintainAspectRatio: false,
    layout: {
      padding: {
        left: 10,
        right: 25,
        top: 25,
        bottom: 0
      }
    },
    scales: {
      xAxes: [{
        time: {
          unit: 'date'
        },
        gridLines: {
          display: false,
          drawBorder: false
        },
        ticks: {
          maxTicksLimit: 7
        }
      }],
      yAxes: [{
        ticks: {
          maxTicksLimit: 5,
          padding: 10,
          // Include a dollar sign in the ticks
          callback: function(value, index, values) {
            return number_format(value) + 'lbs';
          }
        },
        gridLines: {
          color: "rgb(234, 236, 244)",
          zeroLineColor: "rgb(234, 236, 244)",
          drawBorder: false,
          borderDash: [2],
          zeroLineBorderDash: [2]
        }
      }],
    },
    legend: {
      display: false
    },
    tooltips: {
      backgroundColor: "rgb(255,255,255)",
      bodyFontColor: "#858796",
      titleMarginBottom: 10,
      titleFontColor: '#6e707e',
      titleFontSize: 14,
      borderColor: '#dddfeb',
      borderWidth: 1,
      xPadding: 15,
      yPadding: 15,
      displayColors: false,
      intersect: false,
      mode: 'index',
      caretPadding: 10,
      callbacks: {
        label: function(tooltipItem, chart) {
          var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
          return datasetLabel + ':' + number_format(tooltipItem.yLabel);
        }
      }
    }
  }
});

and you can see that I am putting the points here:

data: theDataArray

it is working with one line, but now i want to add a second line, kind of with data like this:

 data: [0, 130, 135, 140, 135, 137, 137, 137, 137, 137, 137, 137],

I am not sure how I would do this. I tried to just put this in right under the other one, but it failed. how would i do this?

What is best practice to remove duplicate/redundant API requests?

So I am working in a React platform that has data that updates every second(I would like to move to web-sockets but its currently only supports gets).Currently, each component makes a fetch request for itself to get the data for the widget. Because the fetch requests are built into the widgets there are redundant api requests for the same data. I am looking for a possible better solution to remove these redundant api requests.

The solution I came up with uses what I call a data service that checks for any subscription to data sources then makes those api calls and places the data in a redux state for the components to then be used. I am unsure if this is the best way to go about handling the issue I am trying to avoid. I don’t like how I need an interval to be run every second the app is running to check if there are “subscriptions”. I am unsure if thats the correct way to go about it. With this solution I don’t duplicate any requests and can add or remove a subscription without affecting other components.

One more thing, the id can change and will change what data I recieve

Here is a simplified version of how I am handling the service.

const reduxState = {
 id: "specific-id",  
 subscriptions: {
    sourceOne: ["source-1-id-1", "source-1-id-2", "source-1-id-3"],
    sourceTwo: ["source-2-id-1", "source-one-id-2"],
  },
  data: {
    sourceOne: { id: "specific-id", time: "milliseconds", data: "apidata" },
    sourceTwo: { id: "specific-id", time: "milliseconds", data: "apidata" },
  },
};

const getState = () => reduxState; //Would be a dispatch to always get current redux state

const dataService = () => {
  const interval = setInterval(() => {
    const state = getState();
    if (state.subscriptions.sourceOne.length > 0)
      fetchSourcOneAndStoreInRedux();
    if (state.subscriptions.sourceTwo.length > 0)
      fetchSourceTwoAndStoreInRedux();
  }, 1000);
};

const fetchSourcOneAndStoreInRedux = (id) =>{
    return async dispatch => {
        try {
            const res = await axios.get(`/data/one/${id}`) 
            dispatch(setSourceOneDataRedux(res.data))
        } catch (err) {
            console.error(err)
        }
    }
}

I am building my components to only show data from the correct id.

PHP call Javascript function but don’t wait response

i’m writing a code in PHP, where a response of a if condition call a Javascript function with SweetAlert2.
Basicaly when a register is updated the button call a PHP function and this one call a Javscript function if it runs with success. Thsi javascript function is a SweetAlert2 which show a message and should wait a click on “Ok” button to redirect the user to another URL.

The problem is the message appears really fast and don’t wait to click, just close the message itself. The redirect is not working as well.

I already try this javascript function out of the PHP code and it is running fine.

How can I fix it please?

PHP code
function UpdateReg() {
  $Titulo =  $_REQUEST['f_titulo'];
  $Descricao = $_REQUEST['f_desc'];
  $Valor = $_REQUEST['f_valor'];
  $cod = $_GET['cod'];

if ($GLOBALS['$conexao']->connect_error) {
    die("Falha de Conexão: " . $GLOBALS['$conn']->connect_error);
  }
  
  $sql = "UPDATE produtos set titulo = '$Titulo', descricao = '$Descricao', valor = '$Valor', WHERE cod_produto = $cod";


  if (mysqli_query($GLOBALS['$conexao'], $sql)) {

    echo "<script>ChangeOk('produto')";
      
  } else {

    echo "Erro: " . $sql . "<br>" . mysqli_error($GLOBALS['$conexao']);
  } 
  
  mysqli_close($GLOBALS['$conexao']);

}

}
Javascript
function ChangeOk(tipo)
    {
      Swal.fire({
        title: "Feito!",
        text: "Registro alterado com sucesso",
        icon: 'success',
        showConfirmButton: true
        }).then((result) => {
          if (result.isConfirmed) {
            window.location = "home.php?tipo=" + tipo
          } 
      })
    }

What is the configuration in Google Chart to lessen the number of number/dates display on the hAxis?

I’m using a line graph in Google Chart and there’s just one thing left I need to configure, the hAxis dates.

The dates have 2 days gap only, like Feb 2, Feb 4, Feb 6, Feb 8, and so on, and so it shows 15 dates on the hAxis. I want to widen the gap maybe by 7 days or lessen the number of dates displayed by just 4 dates. How to achieve that? I can’t seem to find the right config for it here: https://developers.google.com/chart/interactive/docs/gallery/linechart.

Here’s my chart: https://jsfiddle.net/r2wxayn8/

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

      var data = new google.visualization.DataTable();
      data.addColumn('date', 'Date');
      data.addColumn('number', 'Price');

      data.addRows([
        [new Date(2022, 1, 1), 0.2500], [new Date(2022, 1, 2), 0.2500],  [new Date(2022, 1, 3), 0.2600],  [new Date(2022, 1, 4), 0.2700],  [new Date(2022, 1, 5), 0.2800],  [new Date(2022, 1, 6), 0.3000],
        [new Date(2022, 1, 7), 0.2900],  [new Date(2022, 1, 8), 0.3300],  [new Date(2022, 1, 9), 0.3100],  [new Date(2022, 1, 10), 0.3200],  [new Date(2022, 1, 11), 0.3200], [new Date(2022, 1, 12), 0.3200],
        [new Date(2022, 1, 13), 0.3100], [new Date(2022, 1, 14), 0.3200], [new Date(2022, 1, 15), 0.3000], [new Date(2022, 1, 16), 0.3100], [new Date(2022, 1, 17), 0.3000], [new Date(2022, 1, 18), 0.3000],
        [new Date(2022, 1, 19), 0.2900], [new Date(2022, 1, 20), 0.2800], [new Date(2022, 1, 21), 0.2700], [new Date(2022, 1, 22), 0.2700], [new Date(2022, 1, 23), 0.2700], [new Date(2022, 1, 24), 0.2600],
        [new Date(2022, 1, 25), 0.2700], [new Date(2022, 1, 26), 0.2600], [new Date(2022, 1, 27), 0.2500], [new Date(2022, 1, 28), 0.2500], [new Date(2022, 1,29), 0.2400], [new Date(2022, 1, 30), 0.2500]
      ]);

      var options = {
          hAxis: {
            gridlines: {
            color: 'none'
            },
            format: 'MMM dd',
                textStyle: {
                color: '#677185',
                    fontSize: 12,
              bold: true
            }
          },
          vAxis: {
            gridlines: {
            color: '#DFE3EB'
            },
            minorGridlines: {
            color: '#DFE3EB'
            },
                textStyle: {
                color: '#677185',
                    fontSize: 12,
              bold: true
            }
          },
            tooltip: {
                textStyle: {
              color: '#677185',
                    fontSize: 12
            }
          },
          series: {
            0: {
            color: '#26a172'
                        }
          },
                    legend: { position: 'none' },
          curveType: 'function'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

      chart.draw(data, options);
    }

Iterating over deeply nested objects

I have data that looks like this:

{
  FL: [{ID: 1, confirmed: true},{ID: 2, confirmed: false}], 
  TX: [{ID: 3, confirmed: true}], 
  NY: [{ID: 4, confirmed: false}, {ID: 5, confirmed: true}]
}

And I need to be able to loop over each item in this data find the one
who’s ID === a known ID. I’m not sure the best way to approach this.

The only thing that I can come up with is a for-In loop but Id have to map over the arrays after looping over the object so that doesn’t seem very clean.

Is there any method that is clean for handling iterating over such deeply nested data?

Working with big nested object as state in React

Hello fellow developers,

I’m junior developer and I’m working on a project with big nested object (example bellow) which ideally I want to use as react state that can be accessed from multiple places but I don’t know which approach is best for this solution as I don’t have many experiences yet. If you could give me some advice, code example or link to some tutorial or blog, it would be very helpful.

My current approach (example bellow) is to use useContext without useReducer because I just don’t want to just export dispatch because I think is kinda ugly or not programmer friendly as you always have to define different type and payloads. Maybe I could wrap dispatch it in the functions but I’m just not sure about it. I was also thinking about using Redux, but I don’t use that yet and according to what read that it can be overkill for this.

Thank you in advance.

{
    id: string,
    name: string,
    sections: [{
        id: string,
        pos_x: number,
        pos_y: number,
        rows: number,
        columns: number,
        curvature: number,
        skew: number,
        rotation: number,
        section_type: string,
        name: string,
        seats: [{
            id: string,
            row: number,
            column: number,
            is_disabled: boolean,
            category: string,
            name: string,
            created_at: string,
            updated_at: string,
            is_reserved: boolean,
            reserved_at: string,
            status: string,
            ticket: number
        }],
        total_seats: number,
        created_at: string,
        updated_at: string,
        available_seats: number,
        purchased_seats: number,
        reserved_seats: number
    }],
    creator: number,
    account: number,
    is_editable: boolean,
    total_seats: number,
    created_at: string,
    updated_at: string,
    event: number,
    available_seats: number,
    purchased_seats: number,
    reserved_seats: number
}
import React, {createContext, FC, useState} from 'react';
import {Seat, SeatMap, Section} from "../../types/seatmapData";

type UpdateSelectedSectionProps = (section: Section, seatIndex: number) => Section

export interface ISeatMap {
    id: string,
    name: string,
    sections: Section[],
    creator: number,
    account: number,
    isEditable: boolean,
    totalSeats: number,
    createdAt: string,
    updatedAt: string,
    event: number,
    availableSeats: number,
    purchasedSeats: number,
    reservedSeats: number
}

export interface ISeatMapContext extends ISeatMap {
    setName: (name: string) => void;
    setSections: (section: Section[]) => void;
    setId: (id: string) => void;
    setCreator: (creator: number) => void;
    setAccount: (account: number) => void;
    setIsEditable: (isEditable: boolean) => void;
    setTotalSeats: (totalSeats: number) => void;
    setCreatedAt: (createdAt: string) => void;
    setUpdatedAt: (updatedAt: string) => void;
    setEvent: (event: number) => void;
    setAvailableSeats: (availableSeats: number) => void;
    setPurchasedSeats: (purchasedSeats: number) => void;
    setReservedSeats: (reservedSears: number) => void;
    addSectionToSelected: (section: Section) => void;
    removeSectionsFromSelected: (section: Section) => void;
    clearSelectedSections: () => void;
    addSeatToSelected: (section: Section, seat: Seat) => void;
    removeSeatFromSelected: (section: Section, seat: Seat) => void;
    clearSelectedSeats: () => void;
    addSection: (section: Section) => void;
    removeSection: (section: Section) => void;
    removeSelectedSections: () => void;
    updateSection: (section: Section) => void;
    updateSelectedSeats: (updateFunction: UpdateSelectedSectionProps) => boolean;
    reserveSelectedSeats: (reserved: boolean, reservedAt: Date) => void;
    purchaseSelectedSeat: () => void;
    disableSelectedSeats: (disabled: boolean) => void;
    getSeatMap: () => void;
}

export const SeatMapContext = createContext<ISeatMapContext>(null!);

export interface SeatMapProviderProps extends FC {
    children: any;
    initialValue: SeatMap;
}

const SeatMapProvider = ({ children, initialValue }: SeatMapProviderProps) => {

    const [name, setName] = useState<string>(initialValue.name)
    const [sections, setSections] = useState<Section[]>(initialValue.sections)
    const [id, setId] = useState<string>(initialValue.id)
    const [creator, setCreator] = useState<number>(initialValue.creator)
    const [account, setAccount] = useState<number>(initialValue.account)
    const [isEditable, setIsEditable] = useState<boolean>(initialValue.is_editable)
    const [totalSeats, setTotalSeats] = useState<number>(initialValue.total_seats)
    const [createdAt, setCreatedAt] = useState<string>(initialValue.created_at)
    const [updatedAt, setUpdatedAt] = useState<string>(initialValue.updated_at)
    const [event, setEvent] = useState<number>(initialValue.event)
    const [availableSeats, setAvailableSeats] = useState<number>(initialValue.available_seats)
    const [purchasedSeats, setPurchasedSeats] = useState<number>(initialValue.purchased_seats)
    const [reservedSeats, setReservedSeats] = useState<number>(initialValue.reserved_seats)

    const [selectedSections, setSelectedSections] = useState<Section[]>([]);
    const [selectedSeats, setSelectedSeats] = useState<{section: Section, seat: Seat}[]>([]);

    const addSectionToSelected = (section: Section) => {
        setSelectedSections(prev => [...prev, section])
    }

    const removeSectionsFromSelected = (section: Section) => {
        setSelectedSections(prev => prev.filter(s => s.id === section.id))
    }

    const clearSelectedSections = () => {
        setSelectedSections([])
    }

    const addSeatToSelected = (section: Section, seat: Seat) => {
        setSelectedSeats(prev => [...prev, {section: section, seat: seat}])
    }

    const removeSeatFromSelected = (section: Section, seat: Seat) => {
        setSelectedSeats(prev => prev.filter(s => s.section.id === section.id && s.seat.id == seat.id))
    }

    const clearSelectedSeats = () => {
        setSelectedSeats([])
    }

    const addSection = (section: Section) => {
        setSections(prevState => [...prevState, section])
    }

    const removeSection = (section: Section) => {
        setSections(prevState => prevState.filter(s => s.id == section.id))
    }

    const removeSelectedSections = () => {
        if(selectedSections.length == 0) return

        setSections(prevState => {
            const notSelected: Section[] = []
            prevState.forEach(s => {
                let isSelected = false
                selectedSections.forEach(selected => {
                    if(selected.id == s.id) isSelected = true
                })
                if(!isSelected) notSelected.push(s)
            })
            return notSelected
        })
    }

    const updateSection = (section: Section) => {
        setSections((prevState) => {
            const index = prevState.findIndex(s => s.id === section.id)
            sections[index] = section
            return sections
        })
    }

    const updateSelectedSeats = (updateFunction: UpdateSelectedSectionProps): boolean => {
        if(selectedSections.length == 0 || selectedSeats.length == 0) return false
        const updateTime = new Date().toISOString()
        setSections(sections => {
            selectedSeats.forEach(({section, seat}) => {
                const sectionIndex = sections.findIndex(s => s.id === section.id)
                const seatIndex = sections[sectionIndex].seats.findIndex(s => s.id === seat.id)
                const newSection = updateFunction(sections[sectionIndex], seatIndex);
                sections[sectionIndex] = newSection
                sections[sectionIndex].updated_at = updateTime
            })
            return sections
        })
        setUpdatedAt(updateTime)
        return true
    }

    const reserveSelectedSeats = (reserved: boolean, reservedAt: Date) => {
        const updated = updateSelectedSeats((section, seatIndex) => {
            section.seats[seatIndex].is_reserved = reserved
            section.seats[seatIndex].reserved_at = reservedAt.toISOString()
            return section
        })
        if(updated) setReservedSeats(prev => reserved ? ++prev : --prev)
    }

    const purchaseSelectedSeat = () => {

    }

    const disableSelectedSeats = (disabled: boolean) => {
        const updated = updateSelectedSeats((section, seatIndex) => {
            section.seats[seatIndex].is_disabled = disabled
            if(disabled) section.total_seats--
            else section.total_seats++
            return section
        })
        if(updated) setTotalSeats(prev => disabled ? --prev : ++prev)
    }

    const getSeatMap = (): SeatMap => {
        return {
            name: name,
            sections: sections,
            id: id,
            creator: creator,
            account: account,
            is_editable: isEditable,
            total_seats: totalSeats,
            created_at: createdAt,
            updated_at: updatedAt,
            event: event,
            available_seats: availableSeats,
            purchased_seats: purchasedSeats,
            reserved_seats: reservedSeats,
        }
    }

    return (
        <SeatMapContext.Provider value={{
            name, setName,
            sections, setSections,
            id, setId,
            creator, setCreator,
            account, setAccount,
            isEditable, setIsEditable,
            totalSeats, setTotalSeats,
            createdAt, setCreatedAt,
            updatedAt, setUpdatedAt,
            event, setEvent,
            availableSeats, setAvailableSeats,
            purchasedSeats, setPurchasedSeats,
            reservedSeats, setReservedSeats,
            addSectionToSelected,
            addSeatToSelected,
            clearSelectedSeats,
            clearSelectedSections,
            purchaseSelectedSeat,
            removeSeatFromSelected,
            removeSectionsFromSelected,
            getSeatMap,
            addSection,
            removeSection,
            updateSection,
            removeSelectedSections,
            updateSelectedSeats,
            reserveSelectedSeats,
            disableSelectedSeats
        }}>
            {children}
        </SeatMapContext.Provider>
    )
};

export default SeatMapProvider;

vs code power-shell doesn’t recognize npm command

My vs code power-shell doesn’t recognize my command … but cmd works just fine … What is the problem ? … i am currently working on a react js project and i am install npm and yarn then i face these problem… so how can i solve it as soon as possible or i freshly install node and others thing

Kill process.exec function

I have a function to execute a process:

static async runTest() { await process.exec(`start ${currentDir}/forward.py`); }

runTest();

The python script will continue to run until it’s killed, which I don’t know how to do at the moment. So in short, I want to kill this process manually at some point. How I would I do this? Thank you!

Is it valid to mutate an array prop in a child component?

I’ve noticed when pushing to an array that has been passed to a child component as prop, I don’t get the usual ‘Avoid mutating a prop directly’ error. After thinking about it, this makes sense because the array is a reference and if something causes the parent to re-render, the child will render correctly because of this.

Is the proper approach still to emit to the parent and have the parent operate on the array, or is it perfectly valid to operate on the array in the child component since it is a reference?

Vue – Loop through an array with nested objects

I’m fetching a list that I’m trying to loop through that has an object inside. I’m using vue and the array looks like this:

companies: [
  name: "company1"
  id: 1
  type: "finance"
  additionalData: "{"funder":"blabla","idType":5,"number":"2"}"
]

My problem is accessing the different ones inside the additionalData.

This is how far I’ve come:

        <div
            v-for="(company, idx) in companies"
            :key="idx"
        >
          <p class="font-weight-bold text-h6"> {{ company.name }} </p>
          <p class="font-weight-bold"> {{ company.additionalData.funder }} </p>
        </div>

This doesn’t work and I’ve tried a loop inside the loop aswell. When I only print out {{ company.additionalData }} I get the whole object. Can it have something to do with that the object is inside a string? Could I do a computed or something to figure this out or? 🙂

Define characters in a string

I want to be able to reserve 2 or more characters in a string. For example:

let string = "  "
string.unknownMethod("a")

What function do I need in place of unknown method to get this output " a". But if string.unknownMethod("ab") the output should be "ab"