Find path of object property, recursively

I want to print path of object key, dynamically. Here is my code:

   const Tree = ({ data }) => {
     let path = "onboarding";
  
      return Object.keys(data).map((key) => {
        if (Array.isArray(data[key])) {
          path = path + "." + key;
          return (
              <Tree data={data[key]}></Tree> 
          );
        }

        if (typeof data[key] === "object") {
          path = path + "." + key;
          return (
              <Tree data={data[key]}></Tree>
          );
        } else {
          path = path + "." + key;    
          return (
            <input defaultValue={data[key]}
              style={{ fontWeight: "bold" }}
              disabled={!this.props.isEditable}/>

          );
        }
      });
    };

and its my data

  onboarding: {
    enumType: 1,
    key: "key1",
    steps: [
      {
        title: "STEP ONE",
        description: "des1",
        instructions: [
          {
            icon: "step_power",
            label: {
              text: "text1",
              color: "A11111",
              location: "top",
            },
          },
        ],
      },
      {
        title: "STEP TWO",
        description: "des2",
        instructions: [
          {
            icon: "step_power",
            label: {
              text: "text2",
              color: "A11111",
              location: "top",
            },
          },
       ],
    }

And i want to print path of key for each iteration, expected output :

  • “onboarding.enumType”
  • “onboarding.key”
  • “onbording.steps”
  • “onboarding.steps[0]”
  • “onboarding.steps[0].title”
  • . . .
  • “onboarding.steps[1].instructions[0].label.location”

unexpected identifier while compiling ejs

I get the titled error when trying to compile the following

<table>
        <tr >
          <th>First Name</th>
          <th>E-mail</th>
          <th>Last LogIn</th>
        </tr>
        <% for(var i=0; i < users.length; i++) { %>
            <tr>
                <td><%= users[i].name.trim() %></td>
                <td><%= users[i].email.trim() %></td>
                <% if users[i].lastLogIn.trim() !== null %>
                <td><%= users[i].lastLogIn.trim() %></td>
                <% else %>
                <td><0></td>
                <% endif %>
            </tr>
            <% } %>
    </table>

can i get help please

Counting animation Not displaying decimal values

This is the code i have used, i am getting an issue that its not displaying decimal values
i.e : if i give the value 4.5 , it displays only 4, please help me with the problem

$('.count').each(function () {
$(this).prop('Counter', 0).animate({
    Counter: $(this).text()
}, {
        duration: 8000,
        easing: 'swing',
        step: function (now) {
            // $(this).text(Math.ceil(now));
            $(this).text(Math.ceil(now).toString().replace(/(d)(?=(ddd)+(?!d))/g, "$1,"));
        }
    });

});

Return to a specific component/ div in a page when coming from a specific page in React JS (Without anchor tag)

I am working in an application where in a page it have a button. When I select the button it will go to another page.

I am using Push in UseHistory() to pass between pages. I know we can go to a specific div using anchor tag. But I don’t want to use anchor tag. Can anyone help me how can I do that in react.

This is the button component I used to redirect to another page.

const { push } = useHistory();

return (
  <>
    {surveyDisableTime && <SurveyInfoBox />}
    <EmptyList
      image={<NoDataIcon />}
      title={formatMessage({ id: 'event.survey_response.assign_survey.heading' })}
      subtitle={formatMessage({ id: 'event.survey_response.assign_survey.subheading' })}
      onButtonClick={() => push(AppRoute.editEvent.replace(':eventId', event.id), { from: pathname })}
      buttonText={formatMessage({ id: 'event.survey_response.assign_survey.button_label' })}
      disabled={surveyDisableTime}
    />
  </>
);

This is the onclick function -> onButtonClick={() => push(AppRoute.editEvent.replace(':eventId', event.id), { from: pathname })}

In the editEvent I need to go to a specific component. How can I do that?

Thankyou in advance.

Combining Objects based the first two keys and summing values

I currently have an array of objects that looks similar to this where the dates are out of order and each object has the same keys:

const mainArray = [

{Name: John Doe, Date: 1/1/22, Water: 5, Chips: 4, Pizza: 0, HotDog: 0},
{Name: John Doe, Date: 1/5/22, Water: 0, Chips: 0, Pizza: 6, HotDog: 4},
{Name: John Doe, Date: 1/1/22, Water: 5, Chips: 0, Pizza: 0, HotDog: 2},
{Name: Max Dow, Date: 2/7/22, Water: 5, Soda: 4, Pizza: 0, HotDog: 0},
{Name: Max Dow, Date: 2/7/22, Water: 0, Soda: 4, Pizza: 2, HotDog: 1},
{Name: Max Dow, Date: 1/5/22, Water: 1, Soda: 1, Pizza: 0, HotDog: 0},
]

And I would like to combine objects if they share the same name and date. When combining those objects I am also trying to sum like key values together.

The result would look like this:

const mainArray = [

{Name: John Doe, Date: 1/1/22, Water: 10, Chips: 4, Pizza: 0, HotDog: 2},
{Name: John Doe, Date: 1/5/22, Water: 0, Chips: 0, Pizza: 6, HotDog: 4},
{Name: Max Dow, Date: 2/7/22, Water: 5, Soda: 8, Pizza: 2, HotDog: 1},
{Name: Max Dow, Date: 1/5/22, Water: 1, Soda: 1, Pizza: 0, HotDog: 0},
]

I was able to build a function that worked only if the object name and date were in order next to each other however I was unable to find a way to organize all objects by both name and date.

Thank you for your time and effort!

react showing 2 same outcome

i am trying to send a prompt a notification when my sensor hit the threshold. but instead of 1 prompt, i receive 2 of the same prompt.

const TempGraph = () => {

 const [data, setData] = useState([]); // sound , temp, humidity , light , motion .
 const [thresholddata,setThresholdData] = useState([]);
 var result = [];
//  var i = 0;
 //const thresholds = '35';
 function addZero(i) {
  if (i < 10) {i = "0" + i}
  return i;
}

  useEffect(() => {
    const interval = setInterval(() => asyncFetch(),5000) //5000ms = 5sec

    return () => clearInterval(interval) // clear the interval everytime
  }, []);
  /* fetch specific sensor type */ 
  const asyncFetch = async() => {
      await fetch('api')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => {
        console.log('fetch data failed', error);
      });
      
    //fetching threshold data
     await fetch('api')
     .then((response) => response.json())
     .then((json)=>setThresholdData(json))
     .catch((error) => {
       console.log('fetch threshold data failed',error);
     });
     
  };

  if(data.length != 0){
      /* Loop through threshold table to get the same type id */
      for(var x =0;x<thresholddata.length;x++){
        // console.log(thresholddata[i])
          if(thresholddata[x].typeid == data[data.length-1].typeid && thresholddata[x].sensorid == data[data.length-1].sensorid){
          result = thresholddata[x];
            console.log(result)
  
        }
      }
      /* notification when the data value is over the threshold */
      if(result.upperthreshold < data[data.length-1].value){
        openNotificationWithIcon('warning',data[data.length-1].location);
        
      }

  }
   /* graph here */
}

I used a for loop to loop through all the data and make sure the id of them are the same. and when the value of the sensors hits above the threshold it will go to the notification. but the result variable saved 2 same value.

Rerender DOM without using internal state of react and without using DOM manipulation

import React, { StrictMode} from "react";
import ReactDOM from "react-dom";

const rootElement = document.getElementById("root");

function App({store, action}) {
  return <>
        <h1>{store.counter}</h1>
        <button onClick={() => action(true, store)}>
            increment
        </button>
        <button onClick={() => action(false, store)}>
            decrement
        </button>
    </>
}


const store = {
    counter: 0
}
const action = (bool, state) => {
    state.counter = bool ? store.counter + 1 : store.counter - 1 
}
ReactDOM.render(
  <StrictMode>
     <App store={store} action={action}/>
  </StrictMode>,
  rootElement
);

Without changing App function , store and action we have to update the value on DOM .

one solution that I know is : Adding **setInterval function , but this is not most optimized solution .

setInterval(()=>
   ReactDOM.render(
     <StrictMode>
        <App store={store} action={action} />
     </StrictMode>
   );
,10);

Here is the codepen example for the same :
Codepen

How to cast a plain json object to typeorm entity

There is a transformer class called PlainObjectToNewEntityTransformer, if I need to invoke its transform function, I have to pass in the EntityMetadata which requires connection, I think casting doesn’t really need connection. The current workaround is to do the following by just assign in constructor, but this won’t preserve the schema since the field keys are often changed.

@Entity('myentities')
export class MyEntity {
  constructor(partial?: Partial<MyEntity>) {
    if (partial) {
      Object.assign(this, partial);
    }
  }
}

const entity = new MyEntity(json);

I am not sure if the casting can be done in a proper way.

Kendo ui gives an empty data

hi guys look at my code see where is the problem. the problem is that kendo ui showing no data to me, but this will happen after template. and part of url is my controller that works fine but like i said the problem happen from template and says browser can identify ‘id’. so i would happy anyone can help me and new with javascript and jquery!
here is my code:

$("#my-grid").kendoGrid({
            dataSource: {
                type: "Data",
                transport: {
                    read: {
                        url: '/News/LoadNews',
                        dataType: 'json',
                        type: 'GET'
                    },
                },
                pageSize: 20,
            },
            height: 550,
            groupable: true,
            sortable: true,
            pageable: {
                refresh: true,
                pageSizes: true,
                buttonCount: 5,
            },
            columns: [
                {
                    field: "news_title",
                    title: "عنوان",
                },
                {
                    field: "author_name",
                    title: "نویسنده",
                },
                {
                    field: "news_write_date",
                    title: "تاریخ",
                },
                {
                    title: "عملیات",
                    template:'#= editNewsButton(Id) #'
                },
            ],
        });

Why the value function in js is not working

First I created a input element which will take the text input from the user ……
<input style=" font-size: 12 px;" type="text" name="text" id="txt">

Then to this I used some javascript to get the value of the text that the user gives as an input for that I write the below code….
const text= document.querySelector('#txt').value console.log(text)

But with this I am not getting any kind of value actually I am just getting an empty null value in the console can anyone please point out the mistake in the code …

Issue with vue slots, when trying to display data from api call in Vuejs?

HelloWorld.vue

<template>
  <div>
    <div v-for="box in boxes" :key="box.SourceDatabaseName">
      <BaseAccordian>
        <template v-slot:title>{{ box.SourceDatabaseName }}</template>
        <template v-slot:content>
          <div
            v-for="paint in paints"
            :key="paint.TargetDatabaseName"
            class="line"
          >
            <List
              :data="matchingdata"
              :SourceDatabaseName="box.SourceDatabaseName"
            />
          </div>
        </template>
      </BaseAccordian>
    </div>
  </div>
</template> 

<script>
import { boxcontent } from "../assets/boxcontent";
import { paintcontent } from "../assets/paintcontent";
import { matchingcontent } from "../assets/matchingcontent";
import BaseAccordian from "./BaseAccordian.vue";
import List from "./List.vue";
export default {
  name: "HelloWorld",
  components: {
    BaseAccordian,
    List,
  },
  data() {
    return {
      boxes: [],
      paints: [],
      matchingdata: [],
    };
  },
  mounted() {
    boxcontent().then((r) => {
      this.loading = true;
      this.boxes = r.data;
    });
    paintcontent().then((r) => {
      this.loading = true;
      this.paints = r.data;
    });
    matchingcontent().then((r) => {
      this.loading = true;
      this.matchingdata = r.data;
    });
  },
};
</script>

List.vue

<template>
  <div class="">
    <div
      v-for="match in matchingData"
      :key="match.PipelineID"
      :class="{
        green: match.OverallStatus === 'healthy',
        red: match.OverallStatus === 'down',
      }"
    >
      {{ match.OverallStatus }}
    </div>
  </div>
</template>
<script>
export default {
  components: {},
  props: {
    data: {
      type: Array,
      required: true,
    },
    SourceDatabaseName: {
      type: String,
      required: true,
    },
  },
  data: function () {
    return {};
  },
  methods: {},
  computed: {
    matchingData() {
      return this.data.filter(
        (item) => item.PipelineID === this.SourceDatabaseName
      );
    },
  },
};
</script>
<style scoped>
</style>

Present output:-(having issue, unable to see {{overallstatus}} from list.vue component? after checkbox is clicked,)

enter image description here

Expected output:-

enter image description here

After clicking checkbox from the matchingdata array, i am unable to get the response. I am thinking issue with the below code… may be in this code problem??? <List :data="matchingdata" :SourceDatabaseName="box.SourceDatabaseName" />

In List.vue component also, i think data is not filtering correctly and proceeding.

Can you please check my code once, and tell me where exactly i have issue?
code:- https://codesandbox.io/s/vigorous-shtern-lrfeuy?file=/src/components/HelloWorld.vue

Understanding React-hook-form Controller

I am working on a website that has been build before me and it uses a method of the Controller part of react-hook-form that I have not seen before.

This is an example of the code:

const CheckboxController = (props: CheckboxProps) => {
  return (
    <Wrapper>
      <Controller as={CheckboxInput} {...props} /> 
    </Wrapper>
  );
};

With CheckboxInput being a simple material-ui checkbox.

I understand the traditional method of using something like:

const CheckboxController = (props: CheckboxProps) => {
  return(
    <Controller
    name={props.name}
    control={props.control}
    render={({ field }) => (
      <label>
          <Checkbox
            onChange={(e) => field.onChange(e.target.checked)}
            checked={props.checked}
            disabled={props.isDisabled}
            />
            {props.label}
        </label>
      )}
    />
  );
};

But unfortunately the entire site is build upon the <Controller as={}> setup. I cant seem to find any info online about it to figure out how it works. Does anyone know about this method or can point me in the right direction? Thank you.