Combining two JSON objects in JavaScript by matching key values and index positions

After numerous attempts using various methods, I am still unable to achieve the desired outcome. Even implementing nested ng-repeats in Angular to filter down to specific properties proved to be too resource-intensive.

My objective is to retrieve the value of "indices" for each object in the "groups" array, locate the corresponding object in the "person" array by matching the index with the 'indices' value, and then append that value to the respective object in the 'groups' array.

I am solely focused on accomplishing this task in JavaScript upon receiving a response from an API.

Here's an example:

    var obj = {
    "groups": [
        {
          "name": "GroupA",
          "indices": [
            0
          ]
        },
        {
          "name": "GroupB",
          "indices": [
            1
          ]
        },
        {
          "name": "GroupC",
          "indices": [
            2,
            3
          ]
        }
      ],
    "person": [
        {"name": "Archer"},
        {"name": "Lana"},
        {"name": "Mother"},
        {"name": "Barry"}
      ]
  };

Here is the expected final object structure:

 var obj = {
    "groups": [
        {
          "name": "GroupA",
          "indices": [
            0
          ],
        "person": [
          {"name": "Archer"}
          ]
        },
        {
          "name": "GroupB",
          "indices": [
            1
          ],
          "person": [
            {"name": "Lana"}
          ]
        },
        {
          "name": "GroupC",
          "indices": [
            2,
            3
          ],
          "person": [
            {"name": "Mother"},
            {"name": "Barry"}
          ]
        }
      ]
  };

Answer №1

In this scenario, I prefer utilizing forEach for the outer loop instead of map, although it's primarily a matter of personal style:

 obj.groups.forEach(g => g.person = g.indices.map(i => obj.person[i]))
var obj = {
    "groups": [
        {
          "name": "GroupA",
          "indices": [0]
        },
        {
          "name": "GroupB",
          "indices": [ 1 ]
        },
        {
          "name": "GroupC",
          "indices": [2,3 ]
        }
      ],
    "person": [
        {"name": "Archer"},
        {"name": "Lana"},
        {"name": "Mother"},
        {"name": "Barry"}
      ]
  };

  obj.groups.forEach(g =>  g.person = g.indices.map(i => obj.person[i]))
  console.log(obj.groups)

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

How can I declaratively bind the properties in Dojo's _hasDropDown method?

UniqueSearchComponent.html: <div class="${baseClass}"> <div data-dojo-type="dijit/_HasDropDown" data-dojo-props="dropDown: 'containerNode'"> <div data-dojo-type="dijit/form/TextBox" name="${SearchViewFieldName} ...

Output of json.dumps() function in Python 3.5 for objects

I developed a custom class for adding integers representing days to date strings in the format %Y-%m-%d. It was important that the objects of this class could be JSON serialized. Although the addition of days to my objects was functioning correctly, when ...

Incorporating JavaScript and CSS files into a content page of a master page in ASP.NET: Steps to follow

I am facing an issue with adding javascript files and css to a content page of a master page in asp.net. I attempted to include a datetime picker on my ContentPage, but it only works on the masterpage. When I try to add the same code to my contentpage, i ...

Utilizing BBC gelui within Joomla 3.0 for seamless integration

I am currently using Joomla! 3.0 with the Joomlashape Helix template and I am following a tutorial. You can check out the tutorial here. The tutorial mentions that I need to download RequireJS. Can anyone confirm if RequireJS is compatible with Joomla 3 ...

Tips for compressing JSON data in ColdFusion

We are currently experiencing issues when posting a JSON string to the Netsuite ERP platform using cfhttp. We have noticed that we are receiving numerous errors, most of which relate to unterminated string literals. Despite confirming the correctness of ou ...

Guide to dynamically insert rows in HTML using Vue.js based on the selected option

This is the initial row. Depending on the selection made here, different rows will be displayed <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Case Type< ...

Setting up ngModel with information - AngularJS Bootstrap bs-select

Currently, I am managing a website that enables users to create profiles and share activities via a feed. To organize all the created profiles, I have integrated ng-grid into the system. Additionally, I have implemented two buttons that allow users to eith ...

Is there a way to prevent the Material UI Chip component from appearing when there is no content present?

I have developed an application that pulls content from an API and displays it on the screen. Within this app, I have implemented a Material UI Card component to showcase the retrieved information, along with a MUI Chip component nested within the card. &l ...

What is causing the bootstrap nav-bar to not open on smaller screens?

This nav-bar functions properly on screens larger than 640px, but on smaller screens, the menu button does not display the menu items when clicked. You can view the site here. <nav class="navbar navbar-inverse"> <div class="container-fluid" ...

Get image data from Next.JS API and show it in the web browser

I am looking to utilize my own next.js endpoints to request an image that I can then embed into my website. Currently, the issue I am facing is that the image seems to be immediately downloaded and does not display in the browser window. import type { Next ...

Having trouble retrieving Json results after upgrading to the latest Jackson library with jersey version 2.22.1

In my project using jersey v2.21, I am attempting to configure my ObjectMapper with specific settings: Do not include a property if its value is null Sort object properties alphabetically Format dates like this: 2015-06-22T17:57:05.000-07:00 This is wha ...

"Arranging the categories on the xAxis in highcharts based on total values - a step

Is it possible to sort this highchart chart by total? View the highchart chart here The desired final output would be: Name 1 -> 19 Name 4 -> 12 Name 3 -> 10 Name 2 -> 8 See the code snippet below: $(function () { $('#contain ...

What is the best method to delete an attribute from an element using Angular?

When working with Angular, how can I remove an attribute or its value? For example, say I have an ng-click event that I only want to fire once. One approach could be to create a 'self-destruct' in the ng-click event like this: elementClicked = f ...

Ensuring my Mongo connection string is accurate for hosting a remote database with authorization

Having difficulty replicating the MongoDB connection in NodeJS using Mongojs. mongo --host dds-xxxx.mongodb.rds.aliyuncs.com:3717 -u root -p password --authenticationDatabase admin Here is my current code snippet: /* MongoDB setup */ // Define parameter ...

Is it possible for the number returned by setTimeout() in JavaScript to be negative?

Is it possible for a number returned by the setTimeout() function in JavaScript to be negative? Currently, I've observed that the timeoutIds generated are sequentially numbered in Chrome as 1,2,3,4,5,6... While in Firefox, they start from number 4 an ...

The Jquery Ajax call is prompting the download of a JSON file instead of entering the success block

I have been facing an issue with uploading an excel file to a database in MVC5. The upload process is successful, after which the uploaded data should be displayed. I am trying to achieve both of these actions within a single action method. public ActionR ...

Never miss out on the broadcast!

I am working on an Angular Project and I am trying to create an Authentication mechanism. Here is the code for my Login controller: angular.module('authModule') .controller('LoginCtrl', function($rootScope, $location, loginRESTService, ...

Order comments based on their category using vue.js

I have a component form with select filter: <template> <div class="form-group"> <select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id=""> <option ...

Transfer data from a remote desktop

Is it possible to upload a JSON file using the COPY command from a remote desktop? Command: crash --host 192.100.1.15:4200 -c "COPY doc.test FROM '/test.json'" The content of the file: {"id": 1, "name": "foo"} Error: SQLActionException[SQL ...

What is the best way to retrieve the page slug within the layout file in Next.js, specifically when using the app folder structure?

In my latest project, I have implemented a nested layout using the new app folder. Within this layout, I have included a header that appears across all pages in the path www.mysite.com/some-slug. One issue I am facing is with the signup button located in t ...