Guidelines for combining inner objects with their parent in Javascript

I need assistance with using the filter function in Angular.js because it's not working on objects.

Is there a way to merge a nested object into its parent using Javascript?

For example, I have the following data structure:

{
  "data" : [ {
    "character" : {
      "realm" : 1,
      "displayName" : "John",
    },
    "points" : 1388.0,
    "wins" : 84,
    "losses" : 31
  }, {
    "character" : {
      "realm" : 1,
      "displayName" : "Steven",
    },
    "points" : 1363.0,
    "wins" : 96,
    "losses" : 24
  }, {
    "character" : {
      "realm" : 1,
      "displayName" : "Mark",
    },
    "points" : 1322.0,
    "wins" : 154,
    "losses" : 43
  }
]}

and I want to transform it into this format:

{
  "data" : [ {
    "realm" : 1,
    "displayName" : "John",
    "points" : 1388.0,
    "wins" : 84,
    "losses" : 31
  }, {
    "realm" : 1,
    "displayName" : "Steven",
    "points" : 1363.0,
    "wins" : 96,
    "losses" : 24
  }, {
    "realm" : 1,
    "displayName" : "Mark",
    "points" : 1322.0,
    "wins" : 154,
    "losses" : 43
  }
]}

If you have any suggestions or solutions, please let me know!

Answer №1

If you want to transfer properties from one object to another in AngularJS, you can use the extend method (https://docs.angularjs.org/api/ng/function/angular.extend):

for (var i = 0; i < data.length; i++) {
    angular.extend(data[i], data[i].character) //copy properties from character to the parent object
    delete data[i].character; //remove the "character" key
}

Answer №2

Using Vanilla JavaScript:

let data = {
  "info" : [ {
    "user" : { "id" : 1, "username" : "Alice" },
    "score" : 1200.0,
    "wins" : 56,
    "losses" : 28
  }, {
    "user" : { "id" : 2, "username" : "Bob" },
    "score" : 1250.0,
    "wins" : 72,
    "losses" : 19
  }, {
    "user" : { "id" : 3, "username" : "Eve" },
    "score" : 1150.0,
    "wins" : 64,
    "losses" : 35
  }
]}

data.info.forEach(function(item) {
    let user = item.user;
    delete item.user;
    for(let key in user) {
        item[key] = user[key];
    }
});

console.log(data);

Answer №3

Implement

var data = {
  "players": [{
    "info": {
      "server": 1,
      "name": "John",
    },
    "rating": 1388.0,
    "wins": 84,
    "losses": 31
  }, {
    "info": {
      "server": 1,
      "name": "Steven",
    },
    "rating": 1363.0,
    "wins": 96,
    "losses": 24
  }, {
    "info": {
      "server": 1,
      "name": "Mark",
    },
    "rating": 1322.0,
    "wins": 154,
    "losses": 43
  }]
};
for (var key in data.players) {
  data.players[key].server = data.players[key].info.server; // store the server key to the object
  data.players[key].name = data.players[key].info.name; // store the name key to the object
  delete data.players[key].info; // remove info 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

Is it possible to deceive Array.isArray?

Although I have a good understanding of prototypes, I encountered some confusion when I attempted the following: var obj = {}; Object.setPrototypeOf(obj, Array.prototype); console.log(Array.isArray(obj)); // false? What's even more perplexing: var ar ...

Exploiting CORS in Angularjs IONIC

I am making use of the $http.post() function to call an API, but unfortunately, I am encountering a problem with the response. There seems to be an issue with the XMLHttpRequest as it fails to load . The preflight response does not allow the Content-Type ...

Tricks for disabling _blank behavior in jquery?

I'm currently integrating a widget into a webpage using PHP. The widget contains jQuery code that causes all links to open in an external page. Is there a way to override or disable this code so it doesn't impact every link on the page? My prefe ...

Is there a way to properly access and interpret a .log extension file within a React component?

import React from "react"; import "./App.css"; function FileReaderComponent() { const readLogFile = () => { if (window.File && window.FileReader && window.FileList && window.Blob) { const preview = document.getElementByI ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...

Observing modifications in either $pristine or $touched states within the transcluded input

I'm currently in the process of creating a directive for an input element that reacts to changes in the model being modified or interacted with. It seems that the mandatory ngModel reflects modifications in the value and view of the input model, but n ...

Python for Asynchronous HTTP Requests

I am currently working on a Python script to extract the value of the href attribute from an anchor element on a web page. The challenge is that the div element containing the anchor element's content is loaded through AJAX jQuery calls when the web p ...

Determine the width of invisible images using JavaScript/jQuery

Please take a look at the jsFiddle Every time I run it, I am trying to retrieve the width of the images, but the values I get are as follows (check in the JS console) 400 0 575 533 0 ... Some values are zero, and I can't figure out why. It seem ...

Send the value to the <input> tag following each iteration in the functions

I am currently utilizing BootstrapVue. In my code, I have implemented a for loop to retrieve unique numbers from an array, which are stored as this.number. For each iteration of the loop, I use input.push() to add a new b-form-input element (in this case, ...

Transferring user inputs to the server through jQuery-AJAX

I've encountered some issues when trying to send form data inputs to the server. Despite alerting each form input, I keep getting empty alerts. Here's my code snippet: With my current code, it only alerts 0. However, posting normally seems to wor ...

Unable to retrieve event data and integrate it into HTML using jQuery

Just starting out with leaflet and JavaScript, jQuery. I've got an index.html page displaying a map, and want to show the coordinates of the mouse pointer underneath the map when it moves. To achieve this, I have a div element with the id "coordinat ...

How to hide the header on a specific page using Angular

Currently, I am working on an Angular project and my requirement is to hide the header block specifically on the login page. Despite attempting to hide the header on the login page, it seems that my efforts have been unsuccessful so far. Is there anyone wh ...

How can we send data from several input fields using jQuery ajax?

I have several input fields, such as <p>Filter by age</p> <select class="filter-users"> <option value="under20">Under 20</option> <option value="20to40">20 to 40</option> </select> <p& ...

Issues encountered while attempting to verify password confirmation within a React form using Joi

I have been struggling to implement a schema for validating a 'confirm password' form field. While researching how to use Joi for validation, I noticed that many people recommend using the Joi.any() function. However, every time I attempt to use ...

Navigating between applications

Does anyone have suggestions on setting up routing between different apps without disrupting existing code? We want to make the integration process easy when adding a new app to our main application. For example, navigating from an electronics(main app) ...

What is the best way to prevent multiple Material UI cards from expanding simultaneously?

I currently have a dilemma with my Material UI expandable cards. Although everything is functioning correctly, both cards expand simultaneously, which is not the desired behavior. This is how my configuration file is structured: module.exports = { featu ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Deployment replacement in Kubernetes encounters error

I've developed a NodeJS script to deploy review apps to Kubernetes for my GitLab repository, using the Kubernetes NodeJS client. Including abbreviated definitions of Kubernetes resources for thoroughness: const k8s = require('@kubernetes/client ...