Combine an array nested within an object with each key of the object

Alright, let's dive into the structure of these objects:

custom_fields:{
21:{
    edit:true
    required:true
    show:true
   }
}

In my Angular controller, this object is stored under $scope.page.custom_fields. Within this object, there is another structure like so:

custom_fields:{
    21:{
        edit:true
        required:true
        show:true
       }
    22:{
        edit:true
        required:true
        show:true
       }
    data:[
         0:{
            display_name:"Text"
            id:21
            name:"Text"
            value:[
                   0:{"TextHere"}
                  ]
        }
         1:{
            display_name:"Text"
            id:22
            name:"Text"
            value:[
                   0:{"TextHere"}
                  ]
        }
    ]
}

This nested structure is saved as follows:

$scope.page.custom_fields.data = response.data.custom_fields;
The first object consists of sub-objects while the second one contains an array of objects. Now I need to assign the keys from the data object to match the keys in the custom fields object, resulting in a consolidated view like this:

custom_fields:{
    21:{
        edit:true
        required:true
        show:true
        display_name:"Text2"
        id:21
        name:"Text"
        value:[
               0:{"TextHere"}
              ]
       }
}

This assignment should happen within the Angular controller. Each ID from the data array must align with a specific key in custom_fields (e.g., 21:{} matches with data[0:{id:21}]) Since the order is maintained by PHP during processing, a foreach loop in JavaScript is not necessary. Simply sequentially assigning each key from custom_fields.data to its corresponding key in custom_fields will achieve the desired outcome.

Answer №1

data[0:{id:21}]

Sorry, it is not feasible to do that. For more information, check out this link on using a numeric type as an object key.

Answer №2

When working with the $scope.page.custom_fields.21 variable in your code, it may prove to be challenging. It would be more efficient to utilize it in an array format rather than an object. The following code snippet demonstrates how you can achieve this by parsing it into an array of custom field objects.

angular.forEach($scope.custom_fields.data, function(value, idx){ // You may need to adjust this line based on your specific code structure.
   if($scope.custom_fields[value.id]){
       angular.merge($scope.custom_fields.data[idx], $scope.custom_fields[value.id]);
       delete($scope.custom_fields[value.id]);
   } 
});
$scope.custom_fields = $scope.custom_fields.data;
console.log($scope.custom_fields);

Answer №3

let fields_customized = {
  "21": {
    "edit": true,
    "required": true,
    "show": true
  },
  "22": {
    "edit": true,
    "required": true,
    "show": true
  },
  "data": [{
    "display_name": "Text",
    "id": 21,
    "name": "Text",
    "value": ["TextHere"]
  }, {
    "display_name": "Text",
    "id": 22,
    "name": "Text",
    "value": ["TextHere"]
  }]
};

fields_customized.data.forEach(function(item) {
  let obj = fields_customized[item.id];
  for (let attr in item)
    obj[attr] = item[attr];
});
//Remove the data property
delete fields_customized.data;
console.log(fields_customized);

Answer №4

Commenting on the issue at hand, it is my suggestion that a loop be utilized to allocate custom fields accordingly.

let index = 0;
for (let field in custom_fields) {
  if (custom_fields.hasOwnProperty(field)) {
     // If the data is ordered, use the following code, otherwise filter data by custom_fields[field].id
     custom_fields[field].display_name = data[index].display_name;
     custom_fields[field].name = data[index].name;
     custom_fields[field].value = data[index].value;
     index++;
  }
 }

I trust this information proves beneficial for your task.

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

Ways to retrieve the scroll position of content within an iframe

I have a webpage with an iframe that loads another webpage. <iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe> I am looking to retrieve the scroll position of the content inside the iframe using Jav ...

React JS - Breaking down the distinction between PublicTheme and PublicTheme

In my React project, I am currently working on creating the admin dashboard and designing the UI area for user interaction. I have encountered an issue where I am unable to separate the admin theme from the PublicTheme. Even when navigating to "/admin/lo ...

What is the most efficient way to transmit JSON data from a browser to a REST endpoint via Node.js, specifically in gzip format?

Currently working with node.js and express, I have a home page that hits my REST endpoint (PUT) after loading to send some JSON data. The data is not gziped when sending to the endpoint, but I want it to be in gzip form once it reaches the endpoint. Is thi ...

JavaScript fails to function properly on FireFox

I'm currently troubleshooting a script that works in Chrome but not in FireFox. I suspect it's due to the webkit syntax, so I tried converting it to a standard gradient without success. Can you help me identify what's causing the issue? Web ...

Problem with Snowpack's internal module import paths

While working on a project, I am using npx snowpack build --watch instead of the dev command because of a Flask backend. However, I am facing issues with internal imports, specifically modules importing dependencies like Bootstrap importing Popper. The pr ...

Why is it impossible for me to show the title "individual name:"?

<p id="display1"></p> <p id="display2"></p> var player1= { alias: 'Max Power', skills: ['shooting', 'running'] }; $("#display1").append( "<br/>" + "player alias :" + player1.alia ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

When making a POST request with axios, the req.body object appears to be empty. However, when using the 'request' module, the body is populated as expected

Providing some context - My NodeJS server is running on port 3001 and my React application on port 3000. I've configured a proxy in my React application's package.json to redirect all requests to port 3001 - "proxy": "http://localhost:3001" H ...

Managing JSON data through AJAX in ColdFusion

For my external API call using AJAX, I am incorporating a local API setup as an intermediate step. The process is as follows: The Ajax call sends data to localAPI.cfm. Within localAPI.cfm, there is a <cfhttp> tag to forward the data to an external ...

Guide on generating a dynamic loop in JavaScript using the group name as a variable

I have been attempting to organize a group, dynamically ungroup it, and then create a loop with each element of the group. Despite reviewing multiple examples, I have not been able to solve the following issue: The grouping is done based on the "tipo" pro ...

The dialog box in my ajax jquery MVC2 asp.net application is refusing to open

The delete dialog box does not open with my code: view: `<div id="dialog-confirm" title="Delete dialog" style="display: none;"> <p> Are you sure you want to delete the point? </p> </div>` Javascript: `option ...

Continuous polling with Ajax in Rails does not trigger the display of an alert box

Trying to implement ajax polling using the RailsCast tutorial on ajax polling (#229) but encountering an issue where the alert box doesn't pop up after running the server. Here's the code in app/views/quotes/index.js.erb: alert('Hey') ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error: "Err ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

The window.open function is returning a null value after attempting to open the specified

Is there a way to prevent users from opening more than one IFrame window for my application? I have included the following code: <html> <head> <title>Testing Window Opening Limitation</title> <meta http-equiv="Content-Type" cont ...

Error: The "map" property cannot be read if it is undefined in a Django and React application

While I was following the react and django tutorial, I encountered an issue when I added some code for concern with. The error message 'Cannot read property 'map' of undefined' keeps getting thrown. The error location is pointed out ...

Notification access is consistently denied

In my coding work, I rely on Notification.permission to determine if the browser supports notifications or not. Here's a snippet of how I handle Notification.permission in my script: // Verify browser notification support if (!("Notification" in windo ...