Steps to eliminate an array from a collection of arrays stored in an Object

I need help with removing arrays that have a value of 0 in an object.

For example:

dynamic:{"FIRST":[ 0, 0 ,0 ,0], "TEST": [1, 12,123, 12], "KING": [0 , 0 ,0 ,0], "NEXT": [2, 3,4,55]}

Expected outcome:- dynamic:{ "TEST": [1, 12,123, 12], "NEXT": [2, 3,4,55] }

Answer №1

  1. Start by utilizing Object.entries to transform an object into an array,
  2. Proceed to filter the array (employ every if all elements are 0, or some if any element is 0)
  3. Finally, convert back to an object from the filtered array using Object.fromEntries

const transformation = (object) =>
  Object.fromEntries(
    Object.entries(object).filter(([, arr]) => !arr.every((element) => element === 0))
  );

dynamicData = {
  FIRST: [0, 0, 0, 0],
  TEST: [1, 12, 123, 12],
  KING: [0, 0, 0, 0],
  NEXT: [2, 3, 4, 55],
};

console.log(transformation(dynamicData));

Answer №2

To efficiently check and remove empty arrays within an object, you can utilize the Array.prototype.every() method:

const data = { 
    dynamic: {
        "FIRST": [0, 0, 0, 0],
        "TEST": [1, 12, 123, 12],
        "KING": [0, 0, 0, 0],
        "NEXT": [2, 3, 4, 55] 
    }
}

Object.keys(data['dynamic']).forEach(key => {
    if (data['dynamic'][key].every(item => item === 0)) {
        delete data['dynamic'][key];
    }
});

console.log(data);

Answer №3

Obtain the key and then inspect the values in this manner

const dynamic = {
  "FIRST": [0, 0, 0, 0],
  "TEST": [1, 12, 123, 12],
  "KING": [0, 0, 0, 0],
  "NEXT": [2, 3, 4, 55]
}

const result = Object.keys(dynamic).reduce((acc, key) => {
  const val = dynamic[key];
  if (val.some(v => v !== 0)) {
    acc[key] = val;
  }
  return acc;
}, {});

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In React, when pushing to an array, it is the index that gets returned instead of the items

I'm currently working on incorporating a new object into an array that I'm fetching dynamically through my API. Users fill out a form, and the data is transmitted from the form to the state. The initial fetch stores the original array in a React ...

"Encountered an error with resolving the dependency tree during the installation of npm react-facebook-login, known as ERESOLVE

Having trouble installing npm react-facebook-login in my react application due to dependency errors. It's a bit daunting, and I'm hesitant to forcefully install something that could lead to issues down the line. Since I am new to JavaScript, what ...

Testing ng-content in Angular 2

Is there a way to test the functionality of ng-content without the need to create a host element? For instance, let's say we have an alert component - @Component({ selector: 'app-alert', template: ` <div> <ng-conten ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

"Patience is key as we await the resolution of a promise within the confines of an emitter

My goal is to wait for the promise to be resolved before continuing when the someevent event is fired. However, even though I use a then in my code snippet below, it seems that the process shuts down before the slowFunctionThatReturnsPromise is resolved, ...

Verify if a specific key is present in associative arrays

Can you please explain the correct way to check for the existence of a key in associative arrays? For instance: var mydata = { key1: '', key2: { subkey1: { subkey1_1: { value1: '' ...

I'm looking for a button that, when clicked, will first verify the password. If the password is "abcd," it will display another submit button. If not, it

<form action="#" method="post" target="_blank"> <div id = "another sub"> </br> <input type = "password" size = "25px" id="pswd"> </br> </div> <button><a href="tabl ...

Retrieve information from both the client and server sides within NextJS

Looking to integrate a third-party API for data fetching in certain components within my NextJS project. The goal is to have the server pre-render these components with the API for optimal SEO benefits, but also enable client-side fetching of component pro ...

Directives may not function as expected in the invoked view, however, they work properly on the index.html page

Hello there, I've recently started using AngularJS for building applications and encountered a strange issue. I tried looking for similar problems but couldn't find a solution, which is why I'm reaching out to you all! My project specific ...

What are the steps for implementing jquery autocomplete?

I am currently working on a web project using JSP and am attempting to incorporate a basic search feature for users from my database using jQuery autocomplete. However, I am encountering difficulties in grasping how the functionality operates. Just to give ...

When launching the VueJS app in the browser, I am encountering a blank screen with no visible errors. What could be causing this issue?

I've recently embarked on a Vue.js app development journey and everything seems to be in order, except for the fact that the page displays as completely blank in the browser. There are no error messages in the terminal either. Despite my efforts to re ...

Does this method of iterating adhere to Pythonic principles?

I have a list that I need to iterate through, but the code I'm using is not very clean. elements=[] value_and_position=[] for element in items: elements.append(element.get_attribute('class')) Is there a more pythonic ...

What is the best way to reveal the menu options by tapping on the top left icon?

Seeking guidance on how to activate the menu by clicking the top left corner icon. A sample code setup is available in Codepen through this link: https://codepen.io/RSH87/pen/rmgYbo. I require assistance with incorporating the JavaScript file into my React ...

Adjust the color of the output result in real-time

Having trouble changing the color of a JavaScript result based on whether it's positive or negative. I've tried several solutions but can't seem to find one that works. Here is my latest attempt: JavaScript: var calc = (a + b) * c; doc ...

Is there a way to retrieve all indices of an array?

Is there a way to retrieve all the index positions of the elements in an array? [ { "name":"aloha", "age":"18" }, { "name":"hello word" }, { "name":"John Doe", "age":"28" } ] The expected output sho ...

Polymer element created specifically for this project can be seen in the DOM, yet it does not display any content within the

Snippet: <link rel="import" href="../../../../bower_components/polymer/polymer.html"> <link rel="import" href="../../../../bower_components/app-layout/app-drawer-layout/app-drawer-layout.html"> <dom-module id="app-index"> <templa ...

My attempts to load the .mtl and .obj files using THREE.js have been unsuccessful

I've been working on creating a 3D model viewer using three.js, but I'm encountering issues with loading .mtl and .obj files. Despite following a tutorial at , the only model that loads successfully is the female one. Here is the code snippet I ...

Any tips or hacks for successfully implementing vw resizing on the :before pseudo-element in webkit browsers?

When using vw sizes on webkit browsers, a well-known bug can occur where they do not update when the window is resized. The typical workaround for this issue has been to employ javascript to force a redraw of the element by reassigning the z-index upon res ...

Showing data from a Node.js Express application in a Jade template file

I am encountering an issue with my simple jade page where not all variables passed from the javascript route are displaying correctly. I have attempted to implement the solution described in this answer, but it seems to be ineffective in my case. My goal i ...

JavaScript promises to resolve and reject

I am currently working on developing a mobile application using NativeScript. I have created an authorization class with a login() function that contains the following code: export default class NitsEditorAuth { //Finding logged-in user. isLoggedI ...