javascript: deep merging of objects in JS, elimination of empty keys

I have written an assistant to combine objects (deep fusion).

It works and is flexible to add options (like uniq Y replace)

Replace should replace matching properties on the object (but be distributed on existing properties).

The code below works, but I think it could be optimized particularly, since I could NOT find a way to remove empty keys without the use of JSON.parse(JSON.stringify – It feels bad to have to crawl over the entire matrix to do so.

Using Lodash is not an option.

Examples

DATA = {foo: {i: {z: (1)}, x: (1)}}

  • getDeepMerge(DATA, {add:{foo:{q:(1)}}}

    // {foo: {i: {}, x: (1), q: (1)}}

  • getDeepMerge(DATA, {add:{foo:{}}, replace:true}

    // {foo: {}}

  • getDeepMerge(DATA, {add:{foo:{i:{}}} }, replace:true, removeEmpty:true}

    // {add: {foo: {i: {}}, x (1)}}

Code

const removeKey = (key, {(key): _, ...rest}) => rest;

const getNewObj = toAdd => Array.isArray(toAdd) ? getObj(toAdd) : toAdd

const DE_DUPE = (e, i, arr) => arr.indexOf(e) === i

const removeEmptyObj = (o) => {
  let ignores = (null, undefined, ""),
  isNonEmpty = d => !ignores.includes(d) && (typeof(d) !== "object" || Object.keys(d).length)
  return JSON.parse(JSON.stringify(o), function(k, v) {
    if (isNonEmpty(v))
      return v;
  });
}
const getDeepMerge = (ogObj, opts={})=> {
  const { add, uniq=true, replace=false, removeEmpty=false } = opts

  const isObject = obj => obj && typeof obj === 'object';
    return (ogObj, add).reduce((prev, obj) => {
      let _add = {...prev}
      Object.keys(obj).forEach(key => {

        const pVal = _add(key);
        const oVal = obj(key);

        if (Array.isArray(pVal) && Array.isArray(oVal)) {
          _add(key) = pVal.concat(...oVal).filter(uniq ? DE_DUPE : null)
          if(replace){ 
_add(key) = oVal }
          _add = removeEmpty ? removeKey(key, _add) : _add

        }
        else if (isObject(pVal) && isObject(oVal)) {
            _add(key) = getDeepMerge(pVal, {...opts, add:oVal}) 
            if(replace){ 
              _add(key) = oVal
            }
        }
        else {
          _add(key) = oVal
        }
      });
      return removeEmptyObj(_add)
    }, {});
}

Live work demonstration: https://jsbin.com/yuduvukiqe/1/edit?js,console

[ Politics ] Open question: at a Trump rally in Texas, there were at least 1,000 empty seats in an area of ​​6,400 capacity. Even his Trumpets are fed up with him?

Later I saw that he said thousands were waiting outside. There was no one outside, except the protesters. .

javascript – How to fix toDataURL that returns an empty string

I am trying to convert a simple drawing on a canvas into a base64 url, but when I call aDataURL I get an empty string.

The code is below:

var canvas, context, canvasImage;
var cursorPosition = {
  x: undefined,
  y: undefined
};
var mouse;
var color = "rgb(0, 123, 255)";
var size = 10;

function throttle(ms, fn) {
  var lastCallTime;
  return function() {
    var now = Date.now();
    if (!lastCallTime || now - lastCallTime > ms) {
      lastCallTime = now;
      fn.apply(this, arguments);
    }
  };
}

function drawCircle(event) {
  context.beginPath();
  context.arc(cursorPosition.x, cursorPosition.y, size, 0, 2 * Math.PI);
  context.closePath();
  context.fillStyle = color;
  context.fill();
  canvasImage = context.getImageData(
    0,
    0,
    window.innerWidth,
    window.innerHeight
  );
  console.log(canvas.toDataURL());
}
window.onload = function() {
  socket.emit("ai");
  load("left");
  canvas = document.getElementById("number");
  canvas.width = 140;
  canvas.height = 140;
  context = canvas.getContext("2d");
  context.fillStyle = "white";
  context.fillRect(0, 0, canvas.width, canvas.height);
  window.onmousedown = function() {
    mouse = "down";
    console.log("hi");
  };
  window.onmouseup = function() {
    mouse = "";
  };
  window.onmousemove = throttle(0.00000000001, function(evt) {
    if (mouse == "down") {
      var rect = canvas.getBoundingClientRect(), // abs. size of element
        scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X
        scaleY = canvas.height / rect.height; // relationship bitmap vs. element for Y

      cursorPosition = {
        x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
        y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
      };

      drawCircle(event);
    }
  });

  window.ontouchmove = throttle(10, function(event) {
    var rect = canvas.getBoundingClientRect(), // abs. size of element
      scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X
      scaleY = canvas.height / rect.height; // relationship bitmap vs. element for Y

    cursorPosition = {
      x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
      y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
    };
    console.log(cursorPosition);
    drawCircle(event);
  });
};

I can draw on the canvas but when I call it on the console or in the code I get an empty string like this: ""

Any help would be greatly appreciated. I have tried many things online, but nothing helps.

ajax – Table in custom form + empty values ​​in form_state

In a custom way, I created a table element:

  // Table results.
  $form('table') = (
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => ('id' => 'table-results'),
    '#empty' => t('No results.'),
    '#prefix' => '
', '#suffix' => '
' );

This table is ajaxified and updated when I click on a specific button.

I need to get the output HTML from this table in another function. If I use a dpm ($ form_state-> getValue (& # 39; table & # 39;)); I get an empty array. However, the other values ​​(from other fields) are accessible in $ form_state.

// My second function
public function secondfunction(array $form, FormStateInterface $form_state) {
  dpm($form_state->getValue('table')); // -> empty value...
  dpm($form_state->getValue('textfield')); // I get a value
}

What change in my code to solve this problem?

javascript: conditional design based on whether Innerblocks is not empty

This seems like a simple problem, but I can't seem to find an answer. I am using InnerBlocks to stack some paragraphs in a container. If there are no established blocks, I would like not to generate the container at all. Is there (currently) a direct way to do this? It seems that maybe I can test against InnerBlocks, but I haven't seen any documentation that suggests this is reliable.

Google spreadsheets that add more than 20,000 empty rows automatically

I try to expand a Google sheet as needed as I complete the data, but for some reason and without explanation, the sheet suddenly adds up to 25,000 rows while I'm still in row 600. Is there any way to avoid this functionality? Since this began, it has begun to intensively delay the sheet to the point where a complicated conditional formatting configuration takes a couple of minutes to fill in new cells.

python 3.x – It will be useful to create in this problem an empty string este ’and then fill it with the result that will finally be printed

Thank you for contributing to StackOverflow in Spanish with an answer!

  • Please make sure answer the question. Provide information and share your research!

But avoid

  • Ask for help or clarification, or respond to other answers.
  • Make statements based on opinions; Be sure to back them up with references or with your own personal experience.

For more information, see our tips on how to write great answers.

Why the hell is my iPhone storage full if my iCloud is empty?

This has been bothering me for so long, my phone never has storage, no matter how much I delete. I have less than 40 photos and only about 2 very large games. But that's not the problem.

Yesterday my mother saw this problem and chose to buy 50 GB for my phone. That option where you go to the configuration [iCloud, etc.] and choose the plan of 0.99 per month. This increases my iCloud storage from 5GB to 50GB, but my damn phone still has 16GB! My iCloud only has about 3 GB full, so why the hell do the real storage things on my phone not increase or transfer to iCloud? A friend bought this same plan and increased the phone storage to 64 GB in addition to the 50G GB added to iCloud.

Someone please help! This has been killing me for weeks and I'm tired of it!

javascript – TypeScript – Interface. Define a property with an empty object or this object

Take for example this TypeScript code:

interface IBook {
    metadata: {} | {
        title: string;
        author: string
    };
}

const bookOne: IBook = {
    metadata: {}
};

const bookTwo: IBook = {
    metadata: {
        TEST: 'Red Book',
    }
};


As you can see, metadata It can only be an object. But, what I'm trying to figure out, how can I make it an empty object ({}) or if you need to have properties within that object to do it alone title Y author.

I think I know why it's wrong, but I can't seem to find it either. Help?

javascript – DISABLE BUTTON IF A SELECT AND INPUT ARE EMPTY

I have a form with three input [type = "text"], a select and its submit button.

I am trying to disable the form submission button, IF INPUTS and the SELECT They are empty only.

If you have information and something was selected then allow me to send the data.
Any idea how that can be achieved?