Manipulate JSON object in Javascript by adding zeros to fields that are distinct

I am working with a json object that contains three fields: numbers, name, and type. However, not every name has a type associated with it. Here is an example of my object:

myObj=
[{numbers: 10, name: object1, type: type1},
{numbers: 2, name: object1, type: type2}
{numbers: 15, name: object1, type: type3}
{numbers: 16, name: object1, type: type4}
{numbers: 12, name: object2, type: type2}
{numbers: 10, name: object2, type: type4}
{numbers: 1, name: object3, type: type3}
{numbers: 2, name: object4, type: type1}
{numbers: 4, name: object4, type: type2}
{numbers: 3, name: object4, type: type3}
{numbers: 1234, name: object4, type: type4}
]

In order to process this data effectively, I need each type array to have the following structure:

finalNames = [object1, object2, object3, object4];
resultType1Array = [type1NumbersObject1, type1NumbersObject2, type1NumbersObject3, type1NumbersObject4];
resultType2Array = [type2NumbersObject1, type2NumbersObject2, type2NumbersObject3, type2NumbersObject4];
//and so on

The issue arises when an object does not have all four types present. In such cases, I want to insert a zero in the corresponding position within the arrays. For instance:

resultType1Array = [10, 0, 0, 2]
resultType2Array = [2, 12, 0, 4]
resultType3Array = [15, 0, 1, 3]
resultType4Array = [16, 10, 0, 1234]

However, I am facing challenges in implementing this solution as I cannot seem to correctly insert zeros. My current code produces incorrect values. How can I rectify this problem? Here is a snippet of my code:

myObj.forEach(v => names.push(v[Object.keys(v)[1]]));
myObj.forEach(v =>{
if(v.Type === "type1"){
    resultType1Array.push(v[Object.keys(v)[0]]);
}
if(v.Type === "type2"){
    resultType2Array.push(v[Object.keys(v)[0]]);
}
if(v.Type === "type3"){
    resultType3Array.push(v[Object.keys(v)[0]]);
}
if(v.Type === "type4"){
    resultType4Array.push(v[Object.keys(v)[0]]);
}


totalNames = [...new Set(names)];

})

The outcome I currently receive varies depending on the presence or absence of a particular type in the object, resulting in arrays with different lengths. Here is what I get:

resultType1Array = [10, 2]
resultType2Array = [2, 12, 4]
resultType3Array = [15, 1, 3]
resultType4Array = [16, 10, 1234]

How can I accurately place zeros in the appropriate positions within the resultArray for names that lack specific types? Thank you

Answer №1

To solve this problem, you can start by creating an array with a length of 4 (or n if n is the largest object number) and initializing it with zeros. Then simply insert the value at the specified index and ignore the rest.

The code provided below is designed for handling 4 objects initially, but it can be easily adapted to work with any number of objects by adjusting the argument passed to the function to correspond to the largest object number in the dataset.

var myObj = [{
    numbers: 10,
    name: 'object1',
    type: 'type1'
  },
  {
    numbers: 2,
    name: 'object1',
    type: 'type2'
  },
  ...
]

function createArray(arr, largestObjectNumber = 4) {

  var res = [];
  var map = {};

  // Rest of the code remains the same...

}

console.log(createArray(myObj));

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

Is it possible to stream audio and video independently within the same video file?

<video id="video1" width="320" height="176" controls="controls"> <source src="mov_bbb.mp4" type="video/mp4"> <source src="mov_bbb.m4a" type="video/m4a"> </video> I am looking to enhance this video by incorporating an audi ...

What could be the source of the "Uncaught Error: write after end" error occurring in my test cases?

Below is the code I am working with: var Promise = require('bluebird'); Promise.longStackTraces(); var path = require('path'); var fs = Promise.promisifyAll(require('fs-extra')); var clone = require('nodegit').Clone ...

display data from a hashmap in a React component

Struggling with extracting data from a hashmap retrieved from an API for my React application. Here's a snippet of the data: [ [ "d243dc7-6fe8-151b-4ca8-1be528f2b36", "[\"Jonny\",70]" ], ...

Issue with ng-show directive in AngularJS

Currently, I am developing a web app using AngularJS 1.6.6. In my template, I have implemented ng-show in order to recycle it: <div > <br/> <div class="form"> <form data-ng-submit="objectHandlerVM.functions.objectHandl ...

Performing operations atomically within a threaded environment

Are the push and pop operations for arrays atomic? Is it safe to execute i = array.pop ... array.push(i) within a GIL-threaded environment? ...

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Mix up elements in an array using C language

After following an online tutorial, I attempted to shuffle characters in an array. The tutorial focused on integers and didn't involve any user input. However, when I modified the code to fit my requirements, it didn't work as expected. No error ...

Triggering a click event on various instances of a similar element type using the onclick function

Hey there, I'm a newcomer to Javascript. I've been practicing my Javascript skills and trying to replicate something similar to what was achieved in this example: Change Button color onClick My goal is to have this functionality work for multip ...

Is it possible to install in a directory other than the one specified in package.json

I have organized my folders exactly how I want them to be. In one specific folder, all of my configuration files reside (most importantly package.json). I am looking to install this package.json configuration in a different path, specifically c\instal ...

Creating a jQuery slider with customizable name/value pairs or arrays for the values

I am implementing a user-friendly slider for users to choose their position in a range of 1-10 (or something similar). While I know that I can set specific values and steps for the slider, is it possible to have those values correspond to another set? Fo ...

What steps do I need to take in order to invoke a class method post binding?

I am currently taking JavaScript classes class TestA { findUser() { console.log('findUser TEST class') } start() { this.findUser(); } } class TestB extends TestA { } let testB = new TestB(); const A = testB.start.bind(Tes ...

Dividing the results of two arrays obtained through mysqli_fetch_array

I've come up with the following code snippet: while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) { print_r($data['course']); } This results in the following output: Array ( [user_id] => 57 [course] => ...

Creating enduring designs in Next.js

I've been diving into this amazing article and I'm puzzling over the implementation of persistence in Option 4. It seems like you would need to redefine the .getLayout method for each page. I'm uncertain about how nesting logic is handled fo ...

Aggregate functions in jq inspired by SQL GROUP BY operations (including COUNT, SUM, and more)

Previously discussed queries: Tally items under a specific key: jq count the number of items in json by a specific key Add up object values: How do I sum the values in an array of maps in jq? Inquiry How can we replicate the COUNT aggregate function to ...

Error: React Native is unable to access the property 'map' because it is undefined

Having some trouble retrieving API data using axios. Although I can see a response in the console.log, it doesn't display on the screen. Feeling a bit stuck at the moment. export default class PrivacyPolicyScreen extends React.Component { constructo ...

determining the array size in C99

Here is a basic C program: #include <stdio.h> #include <stdlib.h> void process(int array[static 5]){ int i; for(i=0; i<5; i++) printf("%d ", array[i]); printf("\n"); } int main(){ process((int[]){1,2,3}); ...

What is the best way to navigate around and close this modal?

Hey everyone, I've been experimenting with the JavaScript on this codepen and I'm trying to make it so that when you click the background, the modal closes. However, I've run into two issues: The .modal is contained within .modal-backgroun ...

Deciphering complex JSON structures in PHP

I've come across a JSON structure that I need to parse. While I have managed to extract individual nested objects, it feels like there should be a simpler way to achieve this without having to search for each nested structure. Here is an example of t ...

Is there a way to track whether a user has logged into the Google Chrome browser using cookies?

While the LSID cookie can indicate if a user is logged into a Google account, it cannot be reliably used to determine if someone is signed into the Chrome browser because it may also appear when a person is signed into Gmail without being signed into Chrom ...

Adjust the width of the child element to match the parent div's dimensions

In my current setup, there is a parent div that contains a table as a child element. To tidy up the appearance, I am using CSS to hide certain columns in the table rather than applying inline styles. My question is how can I adjust the width of the paren ...