Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141307 articles
Browse latest View live

Convert recursive array object to flat array object

$
0
0

I'm looking for a way to convert this array of recursive objects into a flat array of objects to make it easier to work with.

[
  {
    "name": "bill",
    "car": "jaguar",
    "age": 30,
    "profiles": [
      {
        "name": "stacey",
        "car": "lambo",
        "age": 23,
        "profiles": [
          {
            "name": "martin",
            "car": "lexus",
            "age": 34,
            "profiles": []
          }
        ]
      }
    ]
  }
]

This is the expected output.

[
  {
    "name": "bill",
    "car": "jaguar",
    "age": 30,
  },{
    "name": "stacey",
    "car": "lambo",
    "age": 23,
  },{
    "name": "martin",
    "car": "lexus",
    "age": 34,
  }
]

Each profiles array can have n amount of items, which may or may not have an empty array of sub profiles. Note the converted array objects don't contain profiles after the conversion.

I'm open to using underscore or lodash to achieve this.


Array is still empty after pushed items

$
0
0

My arrays variables are empty Even when I pushed items into these array in forEach in a called function,

they are defined/pushed in controlledCells function, and when I call these variables, arrays are empty but bombCount is okay

I think answer is not complex but I couldn't find, thank you for help

  var clearCells = [];
  var bombCells = [];
  var bombCount = '';
  window.onload = () => {
    setup( difficulty );
  };
  mines.addEventListener( 'click', e => {
   .... controlledCells( cId, checkCellArray );....
  }
  }
  } );
  controlledCells = ( pointedCell, checkCellArray ) => {
    checkCellArray.forEach( e => {
        // debugger;
        let eCell = document.getElementById( e );
        if ( eCell.dataset.bomb == 'true' ) { ** bombCells.push[ e ];
            bombCount++; **
        } else { ** clearCells.push[ e ]; **
        }
    } );
    document.getElementById( pointedCell ).innerHTML = `${bombCount}`; ** console.log( "Bomb:" + bombCount );
    console.log( " clear : " + clearCells ); // empty
    console.log( " bombs :" + bombCells ); //empty**
    bombCount = '';
    makeClearCellsActive( clearCells );
  }

show the latest entry(last), not the first one

$
0
0

So I have multiple arrays and i want to show the data of the last array only. I was trying

const allData = await request.json()
allData = allData[allData.length - 1];

but the second line gives an error. Any ideas guys?? My deadline is in a few hours 😭. I appreciate your help. the function with the issue

const updateUI = async () => {
  const request = await fetch('/all');
  try{
    const allData = await request.json()
    allData = allData[allData.length - 1];
    console.log(allData);
    document.getElementById('date').innerHTML = allData.temperature;
    document.getElementById('temp').innerHTML = allData.date;
    document.getElementById('content').innerHTML = allData.fav;

  }catch(error){
    console.log("error", error);
  }
}

I'm doing an app to get the temp from an API according to the city that the user gives and gives an output temp, date of today, feeling of the user which the user gives as an input. myproject

Remove country from checkout but not from cart

$
0
0

Using the following script in wocommerce Sweden will be removed from both the cart and the checkout

function woo_remove_specific_country( $country ) 
{
   unset($country["SE"]);
   return $country; 
}
add_filter( 'woocommerce_countries', 'woo_remove_specific_country', 10, 1 );

How can I do see so its only visible in the cart when calculating the shipping price and not visible in the Checkout page?

Kind Regards, Martin

if ( is_checkout() ) { 
function woo_remove_specific_country( $country ) 
{
   unset($country["SE"]);
   return $country; 
}
add_filter( 'woocommerce_countries', 'woo_remove_specific_country', 10, 1 );

 } 

Doing following nothing happens when I am in checkout?

Doing following nothines happens as well:

function woo_remove_specific_country( $country ) {
    if ( is_checkout() ) {
       unset($country["SE"]); 
    }
    return $country; 
}
add_filter( 'woocommerce_countries', 'woo_remove_specific_country', 10, 1 );

How to access a partition key in a lambda function?

$
0
0

I have used getItem inside my lambda function.

const ddb = new AWS.DynamoDB({apiVersion: "2012-10-08"});

let params = {
            TableName: "Probability",
            Key: {
                index: randomItemProbability
            }
        };
let item = ddb.getItem(params);
//access partition key of item below

JavaScript, reduce. Need function that makes array to obj

$
0
0

Reduce method is not easy, help me with this problem pls.

i need a function, that receive array with anything, and returns object with fields

{field1, field2, field3, field4}

like in the example: Input:

[true,6,'wow','you are smart, bro']

Output:

{field1: true, field2:1, field3: 'wow', field4: 'you are smart, bro'}

Best way to run a function when page refresh

$
0
0

I am trying to call a function when the page is refreshed. I adding a state if the page is rendered with the data I got from my backend end but I get an warning message "Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state." Even though it works fine (except with the warning message), I dont think this is the best, most efficient way to do it?

If this is the best, most efficient way, how do I fix the waring message?

function Demo() {
  constructor(){
    this.state = {
      username: "unknown",
      rendered: false,
    }
    this.renderUserProfile = this.renderUserProfile.bind(this);
  }

  update(){
    //code to retrieve data from backend node.js *
    this.setState({ username: data });
    this.setState({ rendered: true });
  }

  render(){
    if (!this.state.rendered) {
      this.update();
    }
    return (<p>demo</p>)
  }
}

Thank you for your help!

Is there a best practice way to hide component using react router?

$
0
0

To hide the navbar on the home component I am doing the following

const NavbarComponent = (props) => {
    console.log(props);

    if (props.match.path === '/') {
        return null;
    } else
        return (

it works fine, I need to have access to the router so I can send people to locations dependant on the props object , is there a better way to do it such that I have all router logic in the same place?

this is the current state of my router

    return (
        <div>
            <Router>
                <Route component={Navbar} />

                <Switch>
                    <Route exact path="/" component={Home} />

                    <Route exact path="/api/:city/electronics" component={Electronics} />
                    <Route exact path="/api/:city/labour" component={Labour} />

                    <Route exact path="/api/posts/item/:id" component={ItemDetails} />

                    <Route exact path="/create/:city/:category" component={CreatePost} />
                </Switch>
            </Router>
        </div>
    );


thanks for your time.


How can I lookup data from my google sheet and edit data (html, google apps script)

$
0
0

I have google sheet like this.

I want to search with seatnumber, name and show that row value. If I search 22, Show Class 1, seat number22 name AA contact ~, option1 o, option2 [blank] . and then I want to edit data that option2 [blank] to "o" or the other way and overwrite on google sheet. this is my Html and script. ( and I'm just beginner, so explain easy please.)


    function doGet(){
  return HtmlService.createHtmlOutputFromFile("Index");
}
    function openInputDialog() {
      var html = HtmlService.createHtmlOutputFromFile('Index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
      SpreadsheetApp.getUi().showModalDialog(html, 'Note');
    }

    function itemAdd(form) {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheets()[0];
      var headrownum = 5;
      var tenth = ""
      var nineth = ""
      var currentrow = headrownum;
      var range = sheet.getRange(headrownum, 3, 1, 6)

      while (!range.isBlank()) {
        currentrow++;
        range = sheet.getRange(currentrow, 3, 1, 6)
      }

      var targetrow = sheet.getRange(currentrow, 3, 1, 6);
      
      if (form.class != ""&& form.seatnumber != ""&& form.contact != "") {
        if (form.option1 != "o") {
          nineth = "";
        } else {
          nineth = form.option1;
        }

        if (form.option2 != "o") {
          tenth = "";
        } else {
          tenth = form.option2;
        }
        var values = [
          [form.class, form.seatnumber, form.name, form.contact, nineth, tenth]
        ];

        targetrow.setValues(values);
        var output = 
    HtmlService.createHtmlOutput('<script>google.script.host.close();</script>');
        SpreadsheetApp.getUi().showModalDialog(output, 'Loading...');
      } else {
        var response = Browser.msgBox('Alert', '입력란을 확인하세요', 
  Browser.Buttons.OK);
        openInputDialog();
      }

      return true;
    }
<form>
      class:<br><input type="text" name="class" /><br> 
      seat number :<br><input type="text" name="seatnumber" /><br> 
      name :<br><input type="text" name="name" /><br> 
      contact :<br><input type="tell" name="contact" pattern="[(010)-\d{3,4}-\d{4}]{13}"
    placeholder="010-0000-0000" /><br><br> 
      option1<input type="checkbox" style="transform:scale(1.7)" id="checkbx"
    name="option1" value="o" checked/><br> 
      option2<input type="checkbox" style="transform:scale(1.7)" id="checkbx"
    name="option2" value="o" /><br><input type="button" style="width:100px" value="신청"
    onclick="google.script.run.itemAdd(this.parentNode);" /></body></form></html>

##

enter image description here

Objects are not valid as a react child (In Internet explorer 11 for React 15.4.1)

$
0
0

Objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of App.

AppContainer :

const mapDispatchToProps = (dispatch) => {
    return {

            }
        }
    }
}

Component:

class App extends Component {
    render() {
        return (
        );
    }
}

Above is my render function for app.js. This Code is working fine in google chrome, but when coming to Internet explorer It is not working and it is throwing the above error.

Efficiently validate nested JSON schema/config on front end

$
0
0

I have following JSON config in a typescript project. I would like to validate this on the front-end during run-time. I am looking for a solution similar to node-convict.

I need to validate

  1. unique id / No duplicate Id.
  2. unique name.
  3. required property non empty type
  4. Multiple children types conditionally e.g. if type === folder they should have children prop. it can be an empty array.
  5. Nested Objects at multiple levels.

I've found AJV. AJV docs only refer to whole object being unique not specific properties. I could potentially come up with my own and do some recursive validation. However, I am looking for most efficient solution whether using ajv, another library or an efficient data structure that I could use to validate this.

If using external library it need to be compatible with typescript. I am NOT looking for typescript compile-time validation.

[{
    "type": "folder",
    "name": "",
    "id": 1, // UUID
    "chldren": [{
            "id": 11, // UUID
            "type": "table", // TABLE TYPE
            "name": "Some Table 1",
            "meta": {},
            "dataSource": "..........."
        },
        {
            "type": "folder", // FOLDER TYPE
            "name": "",
            "id": 111, // UUID
            "chldren": [{
                "type": "folder",
                "name": "",
                "id": 1111, // UUID
                "chldren": [{
                    "id": 11111, // UUID
                    "type": "table",
                    "name": "Some Another Table",
                    "meta": {},
                    "dataSource": "..........."
                }]
            }]
        }
    ]
}]

Changing object value with onClick event redo

$
0
0

Sorry to ask this again, but I wanted to add more code for context.

I am making a rock paper scissors game and want to change the playerChoice key when a button the button is pressed.

I want to add an onclick event to each button and run a function that will set the playerChoice property so it references the gameOptions index.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>Lapis, Papyrus Scalpellus</h1>

<h2>Make a Choice</h2>
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id=Scalpellus>Scalpellus</button>
<h2>Game Results</h2>

<script src="script.js"></script>

</body>
</html>


const gameOptions = ["Lapis", "Papyrus", "Scalpellus"];

const newChoice = randomChoice();

console.log(newChoice);

const humanPlayer = {
  playerChoice: gameOptions[0],
};

const computerPlayer = {
  playerChoice: randomChoice(),
};

document.querySelector("#Lapis").onclick = function() {
  humanPlayer.playerChoice = gameOptions[0];
};

document.querySelector("#Papyrus").onclick = function() {
  humanPlayer.playerChoice = gameOptions[1];
};
document.querySelector("#Scalpellus").onclick = function() {
  humanPlayer.playerChoice = gameOptions[2];
};

console.log(humanPlayer);

//Random Choice
function randomChoice() {
  const theChoice = gameOptions[Math.floor(Math.random() * 3)];
  return theChoice;
}

//Players 

function resultText(innerText){
  const paragraph = document.createElement('p');
  paragraph.innerText = innerText;
  document.body.appendChild(paragraph);
}


//Outcomes
function fight(){
  if(computerPlayer.playerChoice === humanPlayer.playerChoice){
     resultText("Its a Tie!20. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
  }else if (computerPlayer.playerChoice === "Lapis"){
    if(humanPlayer.playerChoice === "Papyrus"){
     resultText("Human Player Wins!6. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
    }else if( humanPlayer.playerChoice === "Scalpellus"){
       resultText("Computer Player Wins!5 You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }
  }else if(computerPlayer.playerChoice === "Papyrus"){
    if ( humanPlayer.playerChoice === "Lapis"){
      resultText("Compter Player Wins!4. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }else if( humanPlayer.playerChoice === "Scalpellus"){
      resultText("Human Player Wins!3. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }
  }else if(computerPlayer.playerChoice === "Scalpellus"){
    if ( humanPlayer.playerChoice === "Lapis"){
      resultText("Human Player Wins!2. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }else if( humanPlayer.playerChoice === "Papyrus"){
      resultText("Computer Player Wins!1. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
    }
  }
}

fight()

Does await inside a for loop block the main thread until the entire operation completes?

$
0
0

I am trying to assess whether await inside a for loop blocks the main thread until the entire operation is complete. It is unclear to me what occurs when await is inside a for loop:

for(const work of asyncWork) {
  await work;
}

Option 1:

  work1
  .then(work2)
  .then(work3)
  .then(work4)
  .then(work5)

Option 2:

  work1
  .then(continue);

  work2
  .then(continue);

  work3
  .then(continue);

  work4
  .then(continue);

  work5
  .then(continue);

Make sliding text disappear as it reaches bottom of div

$
0
0

I have a div with id="text" that I am adding text to:

var el = document.getElementById('text');
var p1 = document.createElement('p');
p1.appendChild(document.createTextNode('text to be inputted.'));
el.insertBefore(p1, el.childNodes[0] || null);
<div id="text"></div>

After inputting multiple lines of text, I want the older text at the bottom of the div to disappear.

Can I do this using a max number in the el.childNodes[] array? Or will I have to use collision detection as the text reaches the bottom of the div? Thanks!!!

Initializing new object with random values for each elem in 2D javascript array?

$
0
0

I am trying to do this basic iteration and object initialization but it seems like every row is being created with the object containing same ids. Am I getting crazy?

function makeGrid (cols, rows) {
  const grid = new Array(cols).fill(new Array(rows))
  for (let i = 0; i < cols; i++) {
    for (let j = 0; j < rows; j++) {
      grid[i][j] = {id: random()}
    }
  }
  return grid
}

This is the result: enter image description here


Is there a proper functional programming name for this function (f1, f2, val) => f1(f2(val), val);

$
0
0

I came up with this function (f1, f2, val) => f1(f2(val), val) (javascript notation) and it seemed like it would be useful/common for functional programming. I wanted to know if this function already exists and if it does what it's proper name would be.

(an equivalent question would be what is (f1, f2, val) => f1(f2(val)) called? and the equivalent answer would be composition)

How can I pass data from component and use the data in a method?

Adding a Parameter to Url with javascript

$
0
0

I am trying to add the parameter "referer=" to my url corresponding to the trafic referer of a new session.

I used some of the code from this topic... but it keeps reloading the page in a loop... then the url is like :

https://example.com?refere=facebookreferer=facebookreferer=facebook

Note:

I have been using this solution 1 :

function addOrUpdateUrlParam(name, value)

{
  var ref = document.referrer;
  var refsplit = ref.split(".")[1];
  var href = window.location.href;
  var regex = new RegExp("[&\\?]" + name + "=");
  if(regex.test(href))
  {
    regex = new RegExp("([&\\?])" + name + "=\\d+");
  {

  else
  {
    if(href.indexOf("?") > -1)
      window.location.href = href + "&" + name + "=" + value;
    else
      window.location.href = href + "?" + name + "=" + value;
  }
  if (refsplit != "example") {
  return addOrUpdateUrlParam("referer", refsplit);
}
}

And this solution 2:

function () {
  var ref = document.referrer;
  var refsplit = ref.split(".")[1];
  if (refsplit != "example") {
return location.search += "referer=" + refsplit;
}
}

Edit 1: Thanks to Prasanth I improved the code to :

function  () {
  var ref = document.referrer;
  var refsplit = ref.split(".")[1];
  var currentUrl = location.href;
  var url1 = currentUrl += "?referer="+refsplit;
  var url2 = currentUrl += "&referer="+refsplit;

   if(currentUrl.indexOf("?") < 0) {
    return window.location = url1;
   } else {
    return window.location = url2;
   }
}

However, it is returning both conditions :

https://example.com/?referer=facebook&referer=facebook

Edit 2: So after many attempts, I achieved it by working with the parameters of the url (location.search) instead of the full url (location.href) :

function addRefererParam () {
var ref = document.referrer;  //Get Referrer
var refDomain = ref.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)[0]; //Extract Referrer Domain name for better readability
var params = location.search; //Get Url parameters

  if (refDomain.match(/mydomain|null|undefined/i)) { //check if domain not null or own domain. 
    return params ;
} else {
    return params += "utm_source=" + refDomain; //create new query string with referrer domain
}
}

However, it is no making a persistent query string through browsing... how can I make the new parameters persistent ?

How to pass data from vue instance to component

$
0
0

My Vue is not rendering the branches data property. How can I pass data from the root Vue to the Hello.vue component? I have tried v-bind and passdata but nothing seems to be working. Any help is highly appreciated.

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

 Vue.use(require('vue-resource'))
 var esquery = require('./query') 
 Vue.config.productionTip = false

/* eslint-disable no-new */
var app= new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  data: {
     branches: ''
    },
  methods: {

    search1: function () {
      var self=this
      alert('hi')
      esquery.search().then(function(val){

        self.branches=val.hits.hits[0]._source
        alert(JSON.stringify(self.branches))
      })

     }

    }
  })
app.search1()
//alert (JSON.stringify(branches))

App.vue

<template>
  <div id="app">
    <router-view> </router-view> 
  </div>
</template>

<script>
export default {
  name: 'app',
    props: ['branches']
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Hello.vue
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Design your application smartly</h2>
    <table>
    <tr> Branches </tr>
    <td v-for="branch in branches" :branches="branches"> {{ branch.branchname }}</td>
    </table> 
  </div>
</template>

<script>
export default {
  name: 'hello',
  props: ['branches'],
  data () {
    return {
      msg: 'Welcome to Html'
    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

JavaScript Code-Splitting with hiding the code-endpoints

$
0
0

hey im not really familar with JavaScript or react. So i hope i dont a too easy question:

i want to have a "one-page"-website, and want to change this page dynamically with ajax-request.

I have coded for example code for four visibility-levels (guest-user, normal user, moderator, administrator)

if you log in into my page and you are an admin, you get the JS-Code from all levels. For example in the json-response there is a list with URLs to the Javascriptcode destination.

If you log in as a normal user you should get only the normal-user js-code. The guest-user-js-code you already have; you got that at the time you entered the page.

So i guess the thing is clear, what i want.

But how i should implement this? Are there some ready solutions out there?

https://reactjs.org/docs/code-splitting.html maybe i have to adjust this here?

and maybe there are some good bundlers out there, that i can use, doing that splitting with hiding the endpoint urls (which i get if i have the rights from an ajax-request)?

lg knotenpunkt

Viewing all 141307 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>