How to add a name to a JSON array

I have an JSON array conditions in reactj which has the data as below:

[{
    "attribute": "SHIPPING_METHOD",
    "condition": "EQUAL",
    "favourableValue": "string",
    "combinationType": "AND",
    "combinationConditionType": "TRUE"
}]

But I need a name array like this

    conditionModels: [{
    "attribute": "SHIPPING_METHOD",
    "condition": "EQUAL",
    "favourableValue": "string",
    "combinationType": "AND",
    "combinationConditionType": "TRUE"
}]

How can I achieve this ? I have an API that has this structure with a name?

How to setup WebPack dynamic output dir?

I have this setup currently. The first three entries (app, blocks, react) compile as expected to the rootDir/prod/[name].min.js – This already works

I want the 4th entry (which is a dynamic one). I have this directory: rootDir/gutenberg/blocks/[blockNameDir]/frontend.js; I want the frontend.js file for each of the [blockNameDir] directories to be compiled to the same directory as frontend.min.js.

I figured out how to use the glob for the dynamic entry, but I am stuck at the dynamic output. Thanks in advance.

const path = require('path');
var glob = require('glob');
const outputDir = path.resolve(__dirname, 'prod');


module.exports = {
  mode: 'development',
  entry: {
    app: path.resolve(__dirname, './src/js/app.js'),
    blocks: path.resolve(__dirname, './gutenberg/blocks.js'),
    react: path.resolve(__dirname, './src/js/app-react.js'),

    frontend: glob.sync(
      path.resolve(__dirname, './gutenberg/blocks/**/frontend.js')
    ),
  },
  devtool: 'inline-source-map',
  output: {
    path: outputDir,
    filename: '[name].min.js',
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /.js$/,
        use: ['source-map-loader'],
        enforce: 'pre',
      },
    ],
  },
};

How can I reuse JavaScript inside flask/jinja2 loop?

I have a web page that displays todo lists as seperate div’s/segments. On each todo item is a countdown clock controlled by JavaScript. I can have multiple items in my todo list and would like multiple countdown clocks (one for each item)

The JS runs correctly for the first item in the list but not multiple items. If I delete the first item with a countdown clock then the second item’s clock shows and starts counting down.

How can I make use of the same script for each item in my todo list?

Can I turn it into a function that is called within my loop passing the ID? I have tried this but can’t get it to work.

My best example is simplified below.

{% for todo in todo_list}

// div sections (each section should have its own independent countdown timer)

<div id="segment/{{todo.id}}">
<div id="diff-{{todo.id}}">

// JavaScript inside for loop
// Script to run for each item in todo list and update the div with time/expired based on the todo.id

<script>
var diff = document.getElementById('diff-{{todo.id}}');
var now = moment.utc().format("YYYY-MM-DD HH:mm:ss");
var input_time = '{{todo.created_on}}';
var exam_end_time ='{{todo.eta}}'
var mins = moment.utc(moment(exam_end_time, "HH:mm"),diff(moment(now, "HH:mm"))).format("mm")
var frequency = mins*60
var refreshIntervalId = setIntervan(() => {
   const formatted = moment.utc(frequency--*1000.format("mm:ss");
      diff.innerHTML = formatted;
}, 1000;

setTimeout(() => {
   if(mins === ) {
      diff.innerHTML = "Expired";
      clearInterval(refreshIntervalId);
}},frequency*1000;
</script>
</div>
</div>

{% endfor %}

Delete an entry in a map which key is an array

I’m new to JavaScript Maps and I want to know if there’s a way to delete an entry which key is an array, this is the way I’m trying to do it but it’s not working:

/*
coffee map:

Map(8) {
  'Roast' => 'Dark',
  'Origin' => 'Chiapas',
  304029198 => 'Batch serial number',
  'Packed Date' => 20220134,
  1045 => 'River One Store',
  [ 10, 10, 9 ] => 'Quality Control',
  true => 'Packed',
  false => 'Not packed'
}
*/
coffee.delete([10, 10, 9]);

Thanks!

grouping items from array of object into array in the same object with java script

well my Question is : how can i group some items from an object in new array filed
for Exemple :

   myArray = [
  {Name: "Alex", Age :"13" , Email :" Alex @gmail.com"},
  {Name: "Eva", Age :"24", Email :" Eva @gmail.com"},
  {Name: "Adem", Age :"60", Email :" Adem @gmail.com"},
  {Name: "Jack", Age :"20", Email :" Jack @gmail.com"}
]

The result that i want is :

   myArray = [
  {Name: "Alex",Details :[{Age :"13" , Email :" Alex @gmail.com"}] },
  {Name: "Eva",Details :[{Age :"24", Email :" Eva @gmail.com"}] },
  {Name: "Adem",Details :[{Age :"60", Email :" Adem @gmail.com"}] },
  {Name: "Jack",Details :[{Age :"20", Email :" Jack @gmail.com"}]}
]

Disable dx:ASPxGridView column on Web Forms

I need to disable a specific column on my dx:ASPxGridView when a combobox change to a specific value, but I can’t find the way to disable just that column.

The columns are added with code on C#.

I don’t know if I must do it in Javascript with the client side events or with some event of the dx:ASPxGridView in C#

how to get false if array have string value of index in javascript


function SummPositive( numbers ) {
  var negatives = [];
  var sum = 0;

  for(var i = 0; i < numbers.length; i++) {
    if(numbers[i] < 0) {
      negatives.push(numbers[i]);
    }else{
      sum += numbers[i];
    }
  }

  console.log(negatives);

  return sum;
}

var sum_result = SummPositive( [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52 ] );

console.log(sum_result);

i have some trouble, i dont know how to check if array have index string, return false,
thx all for help me to fix it

PHP + AJAX + multiple button at same page

I’m trying to perform an action using ajax, but for some reason, the post is not working.

<a href="javascript:void(0)" class="btn btn-primary edit" data-id="<?php echo $array[0];?>">Edit</a>
<a href="javascript:void(0)" class="btn btn-primary delete" data-id="123">Delete</a>
<!-- end bootstrap model -->
<script type="text/javascript">
 $(document).ready(function($){

    $('body').on('click', '.delete', function () {

       if (confirm("Delete Record?") == true) {
        var id = $(this).data('id');

        // ajax
        $.ajax({
            type:"POST",
            url: "delete.php",
            data: { id: id },
            dataType: 'json',
            success: function(res){

              window.location.reload();
           }
        });
       }

    });

});
</script>

The problem is that when the delete button is pressed, I get the confirmation but no data is passed to the php file and the page reloads normally.

What could be wrong?

Ps: The jquery and all the css are included on the page, in this question it was removed to facilitate the problem visualization..

How to open desktop program from browser? C# Angular [closed]

Is there a possibility that from the browser, visiting an Angular frontend, you can open a program installed on the computer, developed in C#, and that it can send data to the frontend?

The project is an Angular frontend with a button to login with fingerprint. Due to the limitations of the manufacturer of the fingerprint reader, I can only read the fingerprint from a desktop program.

Therefore, the idea is that the frontend opens that program, reads the fingerprint and obtains a data that is a string in base64 and that string is returned to the frontend so that it continues with the login logic by making a request to the backend (API)

favicon.ico:1 GET http://127.0.0.1:8000/static/favicon.ico 404 (Not Found) even after adding a link

I am trying to fix this error:

favicon.ico:1          GET http://127.0.0.1:8000/static/favicon.ico 404 (Not Found)

The error came after I added a fetch to a JavaScript function.

I have tried adding <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> and <link rel="shortcut icon" href="#">, but neither change anything, and for some reason the error only will occur in the console when I press Ctrl F5. Does anyone know how to fix this?

How to add/remove a scroll event using resize observer

I want to trigger the scroll event when the browser window is 75rem and greater and remove it when the window is smaller.

This only works but doesn’t watch for window size change:

    const mql = window.matchMedia("(min-width: 75rem)")
    const thumb = document.querySelector(".entry-figure")
    const rate = 0.5

    if (mql.matches) {
        document.addEventListener("scroll", () => {
            thumb.style.opacity = (100 / window.scrollY) * rate
        })
    }

I tried the following, but it fails:

mql.addEventListener( "change", (e) => {
    if (e.matches) {
        document.addEventListener("scroll", () => {
            thumb.style.opacity = (100 / window.scrollY) * rate
        })
    }
})

How to execute await code in “chrome.scripting.executeScript” correctly?

I am developing a chrome extension for Udemy but i cannot execute the await code in chrome scripting:

It works until console.log(“Stops here 1”);, for doesn’t go to the next interation.

When I run the main code, outside the extension, directly in the chrome console works fine. But when I try to use the main function in the extension code, not all the code runs.

let clickExamBtn = document.getElementById("clickExam");

async function waitForElm(selector) {
    console.log("funcion...")   ;
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}


function countInArray(array, value) {
    return array.reduce((n, x) => n + (x === value), 0);
}

async function main() {
    var exams = document.querySelectorAll('div.quiz-editor--quiz-editor--2RKDC.default-item-editor--item-editor--3GhNq');
    console.log("Exams: " + exams.length);
    
    for (let j = 0; j < exams.length; j++) {
        var preguntas = exams[j].querySelectorAll('div.assessment-list--assessment-list--1sF23 > ul > li')
        console.log("Questions in exam " + (j + 1) + ": " + preguntas.length);
        document.querySelectorAll('div.quiz-editor--quiz-editor--2RKDC.default-item-editor--item-editor--3GhNq > div:nth-child(1) > div > div.item-bar--right--4qb_w.item-bar--row--3ZgKF > button')[j].click();
        var arr = [];
        for (let i = 0; i < preguntas.length; i++) {                   
            preguntas[i].querySelector('div.assessment-list--assessment-list--1sF23 > ul > li:nth-child(' + (i + 1) + ') > div > button:nth-child(5)').click();
            var querySelector = 'input[type=radio][data-purpose="knowledge-area-option-toggle"]:checked';
            console.log("Stops here 1")  ;   
            await waitForElm(querySelector);
            console.log("Stops here 1")    ; 
            var selectedId = document.querySelector('input[type=radio][data-purpose="knowledge-area-option-toggle"]:checked').id;
            const knowledge_area = document.getElementById(selectedId).parentElement.parentElement.querySelector('input[data-purpose="knowledge-area-option-input"]').value.toUpperCase().normalize();
            arr.push(knowledge_area);
            document.querySelectorAll('div.quiz-editor--quiz-editor--2RKDC.default-item-editor--item-editor--3GhNq > div:nth-child(1) > div > div.item-bar--right--4qb_w.item-bar--row--3ZgKF > button')[j].click();
            console.log("Question " + (i + 1)+ " : "+ knowledge_area);
        };
        const count = {};
        arr.forEach(e => count[e] ? count[e]++ : count[e] = 1 );
        console.log(count);
    };

    return 0;
}




clickExamBtn.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({active: true, currentWindow:true}) 
    await chrome.scripting.executeScript({ 
        target: {tabId: tab.id},
        func: main,
        args: [],
    } ,
    (injectionResults) => {
        console.log('Status: ' + injectionResults);
    } );

})

Accumulator Pattern JS [duplicate]

Is there an easier way to solve this with production level code?

This is my current solution:

// An example of the accumulator pattern
let colors = ["red", "white", "blue"];
let statement = "My favorite colors are ";

for (let i = 0; i < colors.length; i++) {
  color = colors[i];
  if (colors[i] === 'red') {
    statement += color + ", ";
  }
  if (colors[i] === 'white') {
    statement += color + " and ";
  }
  if (colors[i] === 'blue') {
    statement += color + '.'
  }
 }

// Challenge: Make the statement say the following:
// 'My favorite colors are red, white and blue.'

console.log(statement);