Create an instance of an object containing arrays as properties

Is there a way to initialize an object in JavaScript with properties that are arrays?

I am looking to create an object structured like this:

foo = { prop1: [0, 1], prop2: [1, 1], prop3: [0] }

My scenario is as follows:

- If a property doesn't exist, I want to create it as an array and add a number.

- If a property already exists, I need to push the number to that existing array without reinitializing it every time.

This is what I have attempted so far:

var obj = {};
arr.forEach(x => { !obj[x] && obj[x].push(1) });

However, I keep encountering this error:

Uncaught TypeError: Cannot read property 'push' of undefined

This error occurs because the property has not been initialized as an empty array beforehand.

Answer №1

Here is a useful code snippet:

arr.forEach((item) => {object[item] = (object[item] || []).concat(1);})

If object[item] is undefined, it means that it has not been initialized yet. In this case, undefined || [] will result in an empty array [], to which you can then append the value 1, or any other desired data.

Answer №2

Hello, here is a potential solution for you:

let obj = {};
let arr = ["prop1","prop2","prop1","prop3"];
arr.forEach((x) => {
   if(obj.hasOwnProperty(x)) obj[x].push(1);
   else {
      obj[x] = [];
      obj[x].push(1);
   } 
})
console.log(obj);

If obj already has the property x (hasOwnProperty), push the value 1. Otherwise, initialize x as an array property and push 1.

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

Sending an Array to a $resource Route Using POST in an AngularJS ExpressJS Node Application Using MEAN.js

I am struggling with passing an array to the $save method in a $resource function and then retrieving it in my server controller to make changes to the database. Oddly, I can successfully pass a variable using GET requests, but when it comes to passing an ...

Using React and Redux: Sending a function to a child component, triggering it without a handler in the child component

I am experiencing difficulty sending an action through a callback in the code provided below. The action is not being sent as expected. However, if I add the Connected property to a handler like onClick, then the action is executed. How can I make my code ...

Enhance the script tags in Next JS by incorporating data attributes

After compiling my Next JS app, it creates a list of script files for inclusion in the following format. <script src="/_next/static/chunks/main-1234.js" async=""></script> <script src="/_next/static/chunks/webpack-12 ...

Error encountered in React and Redux: Unable to read properties of undefined (specifically 'region')

Whenever a user clicks on edit, I am fetching data (an object) into a redux state and displaying it in a textarea. Here is the code snippet: const regionData = useSelector((state) => state.myReducer.userDetailList.region); The problem arises when this ...

transform the JSON string into a two-dimensional boolean array

I'm looking for a way to transform a JSON string into a 2D array in C#. Currently, I have code that retrieves the text/json from a web browser and saves it as a string. "BoolArray": [ [ true, true, false, ... ], [ true, ...

Verify if the value is a decimal or a point using Java

Currently, I am focused on developing a calculator project that involves the use of a method to separate character and numeric values. However, I have encountered an issue when dealing with decimal values as the result displays as '0'. Here is a ...

when a constant reference is passed in a template function, the array does not degrade to a pointer

This particular query originated from the following source: c++ pass array to function question Since the original poster has already accepted an answer, it is unlikely that anyone will read it now. Upon testing this code with g++, I observed that the a ...

What is the process for converting and transferring the date in Google Apps Script to generate a new event in Google Calendar?

To create an event in GAS, follow this link: https://developers.google.com/apps-script/reference/calendar/calendar#createEvent(String,Date,Date,Object) var event = CalendarApp.getDefaultCalendar().createEvent('Apollo 11 Landing', new Date(& ...

Disable system discord.js

Hey there, I'm experiencing an issue with my code and could use some help. Every time I try to use my mute command, it keeps spamming "You need permission to use command". Below is the snippet of my code: client.on('message', message => { ...

Using React Native with Redux: Filtering Data and Preserving Initial Data in Redux State

For my mobile app, I decided to add a search feature using React-Native & Redux. I fetch data from an API and store it in the redux store so that I have a list of items readily available when the app is running. Now, with a searchbox in place, I want to f ...

How can I use apps script to automatically remove old files from google drive that are over a month old?

Every week, I secure backups of my sheets to a backup folder using the following code. Now, I am looking for a way to automatically delete files older than 1 month from the backup folder. How can I add a script to accomplish this? Backup code (triggered w ...

Trouble with image rotation in jQuery/JavaScript slideshow

For more information, you can visit and click on the Canucks icon, which is located as the third icon below "information architecture and usability." I am attempting to set up a jQuery slideshow by utilizing a template I found online. However, I am encou ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

Validate user credentials using both jQuery and PHP to display an error message if login details are incorrect

Working on a form validation using jQuery and PHP. I am utilizing an .ajax request to the server in order to verify if data has been entered into the form, and execute different actions based on the callback response received from the server. For instance, ...

You need to provide a non-null String in order to display text in a Text widget

As a beginner in flutter development, I am currently working on creating a quiz app where each quiz consists of five questions. However, I have encountered some challenges: 1- I want to ensure that the same question does not repeat within the same quiz, a ...

What is the correct way to parse a JSON array of arrays using the Jackson JSON parser?

I have an API that generates the following JSON: { "monitors": [ [ "/Common/http-cc-ping-any" ] ], "is_alive":true } I am attempting to utilize Spring and Jackson JSON Parser to map this JSON to a POJO. The POJO i ...

Extract the text enclosed by two specific symbols within a string and add it to a new array

I have a string formatted as follows: var str = "-#A This text belongs to A. Dummy Text of A. -#B This text belongs to B. Dummy Text of B. -#C This text belongs to C. Dummy text of C. -#Garbage This string should be ignored" I am looking to convert this ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

What steps can I take to avoid encountering this endless loop?

When passing foo in the arguments of useEffect to use existing array values, it causes an infinite loop because setting new values triggers the f() function again. How can this be resolved? An example of imaginary code is: const [foo, setFoo] = useState&l ...

Is it possible to load a jQuery Mobile dialog without the header?

Within my jQuery Mobile website, I have a button in the header that looks like this: <a href="/foo.html" data-rel="dialog" data-icon="grid">Foo</a> The issue arises when JQM requires me to redeclare the head section with all scripts and CSS. ...