Insert a freshly created element into a multi-dimensional array

I am dealing with a JavaScript object array like the one below.

var satelliteListByGroup = {
    Default: {
        AccessCX1141016091532: {
            name: "IAD_ACS4",
            iname: "IAD_ACS4_core0",
            ra: "[Not assigned]",
            ip: "1.1.1.1",
            status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
            col: "#ff5555",
            fw: "5.0.0.31",
            srv: "Enabled"
        },
        AccessCX1180424080022: {
            name: "IAD_ACS4",
            iname: "IAD_ACS4_core0",
            ra: "[Not assigned]",
            ip: "1.1.1.1",
            status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
            col: "#ff5555",
            fw: "5.0.0.31",
            srv: "Enabled"
        }
    }
};

I am attempting to add a new second-level entry but have been struggling to get it right. I've experimented with different approaches similar to this:

var arr1 = {
            AccessCX11410160916546: {
                name: "IAD_ACS4",
                iname: "IAD_ACS4_core0",
                ra: "[Not assigned]",
                ip: "5.5.5.5",
                status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
                col: "#ff5555",
                fw: "5.0.0.31",
                srv: "Enabled"
            }
        };
        satelliteListByGroup.Default.push(arr1);

In this case, using push is not working correctly. It seems to only function with the primary array name.

Answer №1

push() is a method specifically designed for arrays, whereas Default in this context refers to an object. To merge objects together, you can utilize the Object.assign() method:

The Object.assign() function copies all enumerable own properties from one or more source objects to a target object, returning the resulting merged object.

var satelliteListByGroup = {
    Default: {
        AccessCX1141016091532: {
            name: "IAD_ACS4",
            iname: "IAD_ACS4_core0",
            ra: "[Not assigned]",
            ip: "1.1.1.1",
            status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
            col: "#ff5555",
            fw: "5.0.0.31",
            srv: "Enabled"
        },
        AccessCX1180424080022: {
            name: "IAD_ACS4",
            iname: "IAD_ACS4_core0",
            ra: "[Not assigned]",
            ip: "1.1.1.1",
            status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
            col: "#ff5555",
            fw: "5.0.0.31",
            srv: "Enabled"
        }
    }
};

var arr1 = {
            AccessCX11410160916546: {
                name: "IAD_ACS4",
                iname: "IAD_ACS4_core0",
                ra: "[Not assigned]",
                ip: "5.5.5.5",
                status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
                col: "#ff5555",
                fw: "5.0.0.31",
                srv: "Enabled"
            }
        };
Object.assign(satelliteListByGroup.Default, arr1);
console.log(satelliteListByGroup);

Answer №2

Using the `push` method is not a valid syntax to add a new key to an object. In this scenario, the variable arr1 represents an object. Therefore, you should utilize Object.keys to retrieve the key and Object.values to obtain both the key and values from the arr1 object. Both of these methods return arrays. Since arr1 only contains one value, you can access it by its index.

Next, employ square brackets to generate the key within the Default object.

var satelliteListByGroup = {
  Default: {
    AccessCX1141016091532: {
      name: "IAD_ACS4",
      iname: "IAD_ACS4_core0",
      ra: "[Not assigned]",
      ip: "1.1.1.1",
      status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
      col: "#ff5555",
      fw: "5.0.0.31",
      srv: "Enabled"
    },
    AccessCX1180424080022: {
      name: "IAD_ACS4",
      iname: "IAD_ACS4_core0",
      ra: "[Not assigned]",
      ip: "1.1.1.1",
      status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
      col: "#ff5555",
      fw: "5.0.0.31",
      srv: "Enabled"
    }
  }
};

var arr1 = {
  AccessCX11410160916546: {
    name: "IAD_ACS4",
    iname: "IAD_ACS4_core0",
    ra: "[Not assigned]",
    ip: "5.5.5.5",
    status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
    col: "#ff5555",
    fw: "5.0.0.31",
    srv: "Enabled"
  }
};
let getKey = Object.keys(arr1);
let getVals = Object.values(arr1);

satelliteListByGroup.Default[getKey[0]] = getVals[0]
console.log(satelliteListByGroup)

Answer №3

Make sure you're assigning properties to an object, not just pushing elements into an array. Give this a try-

    obj  ={
       'AccessCX11410160916546':{
        name: "IAD_ACS4",
        iname: "IAD_ACS4_core0",
        ra: "[Not assigned]",
        ip: "5.5.5.5",
        status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
        col: "#ff5555",
        fw: "5.0.0.31",
        srv: "Enabled"
    },
   'AccessCX114101890900-':{
        name: "IAD_ACS6",
        iname: "IAD_ACS4_core2",
        ra: "[Not assigned]",
        ip: "5.5.5.5",
        status: "Permitted, last connected Jan 14, 2019 10:19:12 AM",
        col: "#ff5555",
        fw: "5.0.0.31",
        srv: "Enabled"
    },

   }
for(let key in obj){
 satelliteListByGroup.Default[key]= obj[key];
}

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

What is the best way to utilize a multidimensional array in Node.js and add elements to it?

My goal is to construct a fresh multidimensional array by utilizing data obtained from a third-party API. "output":[ { "is_indb":false, "name":"adam", "tokens":29 }, { "is_indb":true, "name":"aaron", "tokens":2, }, ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

The selected plugin appears to be incompatible with mobile browsers

My project involves implementing the Chosen plugin for a select field, allowing users to type-search through lengthy lists. It functions perfectly on desktop but is disabled on both Apple and Android phones, reverting to the default user interface for sele ...

Assign a property to an object following the execution of the query

I am currently utilizing node express to achieve a specific functionality. I encountered an issue while attempting to populate a field with data from another field. To resolve this problem, I decided to retrieve the value from another query and then assign ...

Loading files using $scriptjs or any other asynchronous loader allows for seamless integration of external resources

Imagine I have developed an AngularJS application that lazy loads controller files (using $scriptjs) and all dependencies when the user navigates to a specific route. This application consists of 3 routes: A, B, and C. My question is: if the user navigate ...

Error: The response from Ajax was abruptly cut off

I am currently developing a thread-messaging system. The process involves using AJAX to send the parent_id to a PHP file which then retrieves threads composed of multiple messages with the same parent_id. Within the AJAX request, the parent_id is sent as ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

Most effective method for populating a mixed type byte array at present

Is there a simple method to organize different pieces of data into specified byte ranges when sending and receiving a byte stream? So far, I've been able to convert individual primitive datatypes into bytes, but I'm looking for a way to allocate ...

Guide on adjusting shipping costs in Stripe based on the customer's address using NodeJS

Utilizing Stripe's Checkout API, I am seeking to provide international shipping options with varying costs based on the country selected at checkout. Is there a method within Checkout that allows me to dynamically adjust shipping costs based on the us ...

Issue with Google Finance JSON response not functioning as expected in Chrome and Firefox browsers, yet appears to be working properly in

I am currently working on a JavaScript project that involves fetching STOCK data from the Google Finance API. When I manually paste the link into my browser, I can successfully retrieve the JSON response: // [ { "id": "22144" ,"t" : "AAPL" ,"e" : "NASDAQ ...

Changing the main directory name in a Three.JS project triggers an unexpected aliasing glitch

Creating a new stackoverflow account just to ask a question is not my usual style, but I am completely baffled by this issue. For months, I have been struggling with a strange bug that causes a glitch in my three.js VR projects on Android. My usual method ...

How to effectively filter nested arrays within Mongoose Populate function

I received the following object from a Mongoose query: let systems = [ { "maxUserLevel": 1, "subsystems": [ { "sections": [], "name": "apple" ...

Is there a way for me to gain access to the ng-repeat scope?

I have a scenario where my ng-repeat generates different elements and I need to perform certain operations, such as creating variables, within the scope of the ng-repeat. Is there a way to access the specific ng-repeat scope? How can I achieve something ...

Python script for calculating the product of an extensive 2D-array

Working with very large 2D-arrays in Python can be time-consuming, especially when multiplying them around 100 times. Each matrix has 32000x32000 elements. Currently, I am using np.dot(X,Y) for multiplication, but it is taking a significant amount of time ...

Display the contents of a <div> tag from one HTML file onto another HTML file

Recently I embarked on learning HTML and came across a peculiar doubt. My goal is to create a section div on the first page that changes dynamically based on the menu item clicked, rather than redirecting to another HTML page. I've experimented with s ...

Is it possible to utilize a JavaScript variable as a node in a JSON stringification request?

After successfully retrieving data from the Bungie API previously, I am now facing a challenge in reading a specific JSON file. http://prntscr.com/k3tin3 I'm currently stuck on how to extract a node from the JSON and then utilize it to request charac ...

React component is being invoked prior to the completion of the fetch operation

In my React code, I am facing an issue with the fetch function not completing in time to pass data to the Chart component. As a result, the chart is rendered without any graph displayed. export const OverviewChart = () => { type dateValue = { x: n ...

Session does not reflect the correct quantity

I have encountered some issues with my account, so I am currently using my brother's account to access the e-commerce website I am working on. My main concern is regarding the handling of quantities on different pages of the website. The website con ...

Discovering the index positions of the nearest lower neighbors within two lists using Python

Imagine you have two numpy arrays, A and B, with different sizes. Array A is a presorted dataset, while array B contains query values. Your task is to find the closest "lower" neighbor in array A for each element in array B. Here's an example code sni ...