Learn the process of transferring a complete JSON object into another object using Angular

I'm having trouble inserting one object into another. My JSON object is multidimensional, like this:

{
   "item1":{
      "key":"Value",
      "key":"Value"
   },
   "item2":{
      "key":"Value",
      "key":"Value"
   },
   "item3":{
      "key":"Value",
      "key":"Value",
      "subItem3":{
         "key":"Value",
         "key":"Value"
      }
   }
}

I need to insert item3 into item2 like this:

{
   "item1":{
      "key":"Value",
      "key":"Value"
   },
   "item2":{
      "key":"Value",
      "key":"Value",
      "item3":{
         "key":"Value",
         "key":"Value",
         "subItem3":{
            "key":"Value",
            "key":"Value"
         }
      }
   }
}

If you have any advice on how to accomplish this, I would greatly appreciate it.

Answer №1

The current question lacks clarity. Moreover, there is an issue with the provided input object as it contains duplicate properties, which is not allowed. To address these problems, you may consider utilizing both Object.entries() to obtain an array of the object's key-value pairs and Array#reduce to convert it into the desired format

Give this a try

const data = {
  "item1": {
    "key1": "Value1",
    "key2": "Value2"
  },
  "item2": {
    "key1": "Value1",
    "key2": "Value2"
  },
  "item3": {
    "key1": "Value1",
    "key2": "Value2",
    "subItem3": {
      "key1": "Value1",
      "key2": "Value2"
    }
  }
};

const result = Object.entries(data).reduce((accumulator, [key, value]) => {
  if (key === 'item3')
    accumulator['item2'] = { ...accumulator['item2'], [key]: value };
  else 
    accumulator[key] = value;
  return accumulator;
}, Object.create(null));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0px }

Answer №2

In the hypothetical scenario, let's imagine the object is stored in a variable called myObject.

myObject.item2.item3 = myObject.item3;
delete myObject.item3;

Answer №3

Give this method a go.

let data = {
       "value1":{
          "key":"Value",
          "key":"Value"
       },
       "value2":{
          "key":"Value",
          "key":"Value"
       },
       "value3":{
          "key":"Value",
          "key":"Value",
          "subValue3":{
             "key":"Value",
             "key":"Value"
          }
       }
    }

    data.value2.value3 = data.value3
    delete data.value3

    console.log(data)

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 challenges of handling dynamic controls and reactive forms in Angular when editing, and ways to effectively update their values

I am currently working on creating an inline dynamic form using reactive forms. I have successfully added a new object and looped it in the DOM, but when I press the edit button, it doesn't work and produces errors in the console. Inside the object, t ...

Show a Toast in React without relying on useEffect to manage the state

I have successfully implemented the Toast functionality from react-bootstrap into my application using the provided code. However, I am unsure if it is necessary to utilize useEffect to set show with setShow(items.length > 0);. Would it be simpler to ...

How to dynamically deserialize a Newtonsoft JSON into an object using VB.NET

ANSWER provided involves utilizing LINQ to JSON and the JObject for converting JSON into a usable object dynamically. Below is the code snippet that demonstrates this conversion, followed by the original query. 'Parse JSON string into a JObject acces ...

Steps to display images within a div from a specific directory

Recently, I have encountered a challenge that involves retrieving images from a specific directory, regardless of the number of images present, and then displaying them in a div using an unordered list. I attempted the following code snippet, but unfortuna ...

Set the default value for a form control in a select dropdown using Angular

I've been struggling to figure out how to mark an option as selected in my select element, but I haven't had any luck. I've tried multiple solutions from the internet, but none of them seem to be working for me. Does anyone out there have ...

Angular's DomSanitizer not functioning properly with the Transform css property

I have a question regarding my use of DomSanitizer. The background css property seems to be working fine, but the transform property is not displaying any output. I'm unsure where I might be going wrong in my implementation. In my Angular 8 code: i ...

Broadcast the latest N occurrences

I am working on an Angular 6 application where I want to display the most recent N events from a continuous stream of events coming from a web-socket. Currently, the data is shown using RxJS Observable<Event[]>: <div *ngFor="let event of (wsEven ...

The concept of Typescript involves taking a particular type and generating a union type within a generic interface

Picture a straightforward CollectionStore that contains methods for creating and updating a record. The create() method takes in a set of attributes and returns the same set with an added id property. On the other hand, the update method requires the set t ...

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

When I select a checkbox in Angular 2, the checkall function does not continue to mark the selected checkbox

How can I check if a checkbox is already marked when the selectAll method is applied, and then continue marking it instead of toggling it? selectAll() { for (let i = 0; i < this.suppliersCheckbox.length; i++) { if (this.suppliersCheckbox[i].type == " ...

Having trouble with json encoding in Go

Just recently delved into go programming, and I'm trying to connect to mongodb, search, create a service, and use it for angular. I've managed to do most of it, but I'm encountering an issue with json.marshal(). Can anyone point out what I&a ...

Changing the color of the pre-selected date in the mat-datepicker Angular component is a key feature that can enhance the

Is there a way to adjust the color of the preselected "today" button in mat-datepicker? https://i.stack.imgur.com/wQ7kO.png ...

Creating a JSON string that contains HTML output from PHP

My PHP code generates JSON output. <?php $html = utf8_encode($gegevens['tekst']); $html = htmlentities($html); //$html = htmlspecialchars($gegevens['tekst'], ENT_QUOTES, 'UTF-8'); echo json_encode(array( 'titel' ...

What is the syntax for assigning a public variable within a TypeScript function?

I am finding it challenging to assign a value to a public variable within another function. I seem to be stuck. export class MyClass{ myVar = false; myFunction(){ Module.anotherFunction(){ this.myVar = true; } } } ...

Output JSON data using Javascript

Here is some JSON data I am working with: { "lang": [ { "SECTION_NAME": { "english": "My title" }, "SECTION_NAME_2": { "english": "My title" } } ] } I ...

Error with the type of CanvasGradient in the NPM package for converting text to image

I attempted to generate an image using a specific text by utilizing npm's text-to-image package, but encountered an error during typescript compilation. The errors I encountered upon running the typescript compilation command are related to files with ...

Manipulating data in Angular using RxJs - Creating, Reading,

public ngOnInit() { this.fetchUsers(); } public fetchUsers() { this.userService.getUsers(this.listId).pipe(take(1)).subscribe(data => { if (data.result.length) { this.users = data.result; } else { const user = new UserModel(); ...

Having numerous occurrences of the identical root application in Angular 2

Our team has been successfully integrating Angular 2 into a legacy page, gradually enhancing its user-friendliness by replacing prerendered backend widgets with angular modules. However, we have encountered a challenge that I am unsure how to address: I h ...

The Maven build encountered an error while trying to execute a goal, resulting in the inability to

I'm currently working on a Windows 7 computer and I've received some code that requires me to execute "mvn install" in order to build the application. However, when I try to run this command, I encounter the following error: Failed to execute ...

Compose a message directed to a particular channel using TypeScript

Is there a way to send a greeting message to a "welcome" text channel whenever a new user joins the server (guild)? The issue I'm running into is that, when I locate the desired channel, it comes back as a GuildChannel. Since GuildChannel does not hav ...