Creating nested objects in Javascript involves adding an object inside another object

There are two objects that I have:

    obj1= 
{ 
      '201609': 52,
      '201610': 54,
      '201611': 56,
       metric: 'promotionsOut',
       careerLevelGroups:
       [ { '201609': 52,
           '201610': 54,
           '201611': 56,
           careerLevelGroup: 'Associate' 
          } 
        ] 
    }

        obj2= 
{'careerLevels': [{
            '201609': 21,
            '201610': 22,
            '201611': 23,
            'careerID': 10000120
        },
        {
            '201609': 31,
            '201610': 32,
            '201611': 33,
            'careerID': 10000130
        }
    ]
}

I now want to merge obj2 in a way that the resulting object is as follows:

result = 
{
        "201609": 52,
        "201610": 54,
        "201611": 56,
        "metric": "PromotionsOut",
        "careerLevelGroups": [{
            "201609": 52,
            "201610": 52,
            "201611": 56,
            "careerLevelGroup": "Associate",
            "careerLevels": [{
                    "201609": 21,
                    "201610": 22,
                    "201611": 23,
                    "careerID": 10000120
                },
                {
                    "201609": 31,
                    "201610": 32,
                    "201611": 33,
                    "careerID": 10000130
                }
            ]
        }]

    }

I've been attempting to achieve this by using the push method, like so:

let onlyCLs = obj2;
 metric_clg_json.careerLevelGroups[0].careerLevel.push(onlyCLs);

However, I'm facing issues with this approach. It seems like I might require a loop logic to access the "careerLevels" node before inserting obj2 right below it.

Answer №1

Avoid using the push method for inserting items into an array. Instead, assign an array to a property directly.

To achieve this, set obj2.careerLevels as the value for the careerLevels property of obj1.

obj1 = {
  '201609': 52,
  '201610': 54,
  '201611': 56,
  metric: 'promotionsOut',
  careerLevelGroups: [{
    '201609': 52,
    '201610': 54,
    '201611': 56,
    careerLevelGroup: 'Associate'
  }]
}

obj2 = {
  'careerLevels': [{
      '201609': 21,
      '201610': 22,
      '201611': 23,
      'careerID': 10000120
    },
    {
      '201609': 31,
      '201610': 32,
      '201611': 33,
      'careerID': 10000130
    }
  ]
}

obj1.careerLevelGroups[0].careerLevels = obj2.careerLevels;

console.log(obj1);

Answer №2

To properly integrate obj2 into the array careerLevelGroups of obj1, follow these steps:

var obj1= 
{ 
  '201609': 52,
  '201610': 54,
  '201611': 56,
  'metric': 'promotionsOut',
  'careerLevelGroups':
   [ { '201609': 52,
       '201610': 54,
       '201611': 56,
       'careerLevelGroup': 'Associate' 
      } 
    ] 
}

var obj2 =  {
    'careerLevels': [{
          '201609': 21,
          '201610': 22,
          '201611': 23,
          'careerID': 10000120
      },
      {
          '201609': 31,
          '201610': 32,
          '201611': 33,
          'careerID': 10000130
      }
  ]
}

obj1.careerLevelGroups[0]['careerLevels'] = obj2['careerLevels'];
console.log(obj1);

Answer №3

obj1.careerLevelGroups[0].careerLevels = obj2.careerLevels

obj1= { 
  '201609': 52,
  '201610': 54,
  '201611': 56,
   metric: 'promotionsOut',
   careerLevelGroups:
   [ { '201609': 52,
       '201610': 54,
       '201611': 56,
       careerLevelGroup: 'Associate' 
      } 
    ] 
}

obj2={'careerLevels': [{
            '201609': 21,
            '201610': 22,
            '201611': 23,
            'careerID': 10000120
        },
        {
            '201609': 31,
            '201610': 32,
            '201611': 33,
            'careerID': 10000130
        }
    ]
}
obj1.careerLevelGroups[0].careerLevels = obj2.careerLevels
console.log(obj1)

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

The message I'm attempting to include in the request is not being transmitted along with the request

Currently, I am facing an issue while using Thunder Client to send requests with a POST method. Despite including the body contents and setting the content-type to application/json in the header, whenever I try to access req.body in the request section, ...

Setting values for a volatile array in C++

My dilemma involves managing a dynamic array of MyType elements stored in shared memory, which has been set up using CreateFileMapping and similar functions: volatile MyType *arr; The challenge I'm facing is how to successfully assign a value to an ...

Time-driven occurrences in HTML

I want to create a daily event, like an alert box or a message displayed in a window, at 10 am on my webpage. How can I achieve this without constantly checking the time and wasting resources? ...

Creating markers for every value in a table using Google Maps API v3

Looking for some guidance here. I have a table with multiple values that I need to process using a function. Could someone help me with a suitable loop in jQuery or JavaScript that can achieve this? I'm still learning the ropes of these languages. My ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

Running a setTimeout function within the context of a jQuery each

My goal is to animate characters one by one, but for some reason the following code isn't functioning as expected: $('.overlay-listing').hover(function(){ var idx = 1; $('.strip-hov span', this).each(function(){ if ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

Tips for creating code that continues to run in the "background" endlessly

I am facing the challenge of working with an API that has a limited request capacity, and I want to avoid exceeding this limit by having users directly access the endpoint. My solution involves using JavaScript to automate periodic requests to the API, whi ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

Changing the disabled textfield colour in Material-UI

I am looking to enhance the visibility of disabled text in a textfield by making it darker than the current light color: https://i.sstatic.net/Iw6Dp.png I have attempted to achieve this using the following code snippet: import { withStyles } from ' ...

Is your Material UI Responsive Appbar overlapping the main content? Looking for a solution to address this issue?

Currently, I am in the process of developing a website that incorporates a responsive-based app bar with an attached drawer. The design concept I am following can be located at this link, which I have been modifying to suit my needs. However, I have encoun ...

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

Navigating through data stored in a 2-dimensional array using a double pointer within a struct (in C programming language)

After creating an M[x][y] array, a pointer to the array *p_M[x], and a pointer to the pointer **d_p_M, the results inside the function were as expected. However, upon trying to access the elements in main, the results became confusing. I'm having dif ...

Transform the entire division into a clickable link, excluding a specific subdivision that should have its own separate link

I need to create a product layout page where products will be displayed with an image, person's name, title, and description. The challenge is that all of these elements should have one common link except for the person's name that needs a separa ...

Troubleshooting Axios errors when using createAsyncThunk function

Can someone help me with handling errors in createAsyncThunk using TypeScript? I attempted to declare the returned type and params type with generics, but when it came to error handling typing, I found myself resorting to just using 'any'. Let& ...

What is the best way to set up a variable in Typescript that will be assigned the value of an asynchronous request once it is completed?

As a newcomer to typescript, I encountered an issue that hadn't occurred in my previous project. It appears that declaring a variable before an API request inside a try-catch block leads to typescript errors when attempting to use this variable after ...

The connections of directives

In my Angular application, I am encountering an issue while trying to enhance the functionality of a third-party directive with my own custom directive. The problem lies in the order of instantiation of these directives. The intended usage of the directiv ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Is it unwise to rely on Sequelize for validating objects that are not stored in a database?

Currently, I am utilizing Sequelize as my ORM and find the powerful built-in model validation to be quite impressive. I am contemplating leveraging Sequelize as a schema validator in specific scenarios where there would not be any actual database writes. E ...