Tips for comparing and adding a field to a sub-array within an object

I have a scenario where I have two objects. The first object contains name and id, while the second object has some fields along with the id field from the first object.

For Example:

FirstObj = [{
  _id: '48765465f42424',
  Name : 'Sample'
},{
  _id: '48765465f654654',
  Name : 'Sample1'
}]
secondObj = [{
  Field1 : 5464,
  subarray : [{
        Field2 : 14654,
        Field3 : { IsActive : true,
                     FirstObjid : '48765465f42424'
                  },
        Field4 : { IsActive : true,
                     FirstObjid : '48765465f654654'
                  }
            }]
    },
    {
  Field1 : 2145,
  subarray : [{
        Field2 : 544644,
        Field3 : { IsActive : true,
                     FirstObjid : '48765465f654654'
                  },
        Field4 : { IsActive : true,
                     FirstObjid : '48765465f42424'
                  },
        }]
    }]

In this case, I need to compare both objects and add the corresponding name from the first object to the secondobj's subobj alongside the FirstObjid field.

The Expected Output should be:

 secondObj = [{
  Field1 : 5464,
  subarray : [{
        Field2 : 14654,
        Field3 : { IsActive : true,
                     FirstObjid : '48765465f42424',
                    Name : 'Sample'
                  },
        Field4 : { IsActive : true,
                     FirstObjid : '48765465f654654',
                    Name : 'Sample1'
                  }
            }]
    },
    {
  Field1 : 2145,
  subarray : [{
        Field2 : 544644,
        Field3 : { IsActive : true,
                     FirstObjid : '48765465f654654',
                     Name : 'Sample1'
                  },
        Field4 : { IsActive : true,
                     FirstObjid : '48765465f42424',
                    Name : 'Sample'
                  },
        }]
    }]

If you are thinking how to achieve this, keep reading!

Answer №1

Give this a shot

secondObj.subarray.forEach(function(element){
if(element.FirstObjid==FirstObj._id)
    element.Name = FirstObj.Name
})

Answer №2

Utilize the map function to compare object ids in this way

var secondObj =  [{
  Field1 : 5464,
  subarray : [{
        Field2 : 14654,
        Field3 : 'sfsadf',
        FirstObjid : '48765465f42424'
        }]
    },
    {
  Field1 : 2145,
  subarray : [{
        Field2 : 544644,
        Field3 : 'awrfsa',
        FirstObjid : '48765465f654654'
        }]
    }]
    
 var FirstObj = [{
  _id: '48765465f42424',
  Name : 'Sample'
},{
  _id: '48765465f654654',
  Name : 'Sample1'
}]

secondObj.subarray = secondObj.map(o => o.subarray.map(k=> FirstObj.map(l=> { 
  if(l._id == k.FirstObjid){
     k.Name = l.Name
  }
  return o;
})))
 

console.log(secondObj)
 

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

What is the best way to set up multiple unique uglify tasks in grunt?

I am facing issues when trying to create multiple Uglify tasks in Grunt. Currently, I have to toggle between commenting and uncommenting a task to get it to work properly. I need assistance in generating two separate minified .js files using this plugin ...

Learn the process of playing a video in an HTML5 video player after it has finished downloading

// HTML video tag <video id="myVideo" width="320" height="176" preload="auto" controls> <source src="/server/o//content/test2.mp4" onerror="alert('video not found')" type="video/mp4"> Your browser does not support HTML5 vid ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

Tips for displaying the data on top of individual column bars: Hightcharts, Vue-chartkick, and Cube Js

Looking for assistance with adding value labels to the top of each column bar in a Vue chart using chartkick and highcharts. https://i.sstatic.net/c4Bwc.jpg Check out the image above to see my current output. <template> <column-chart lable= ...

I was disappointed by the lackluster performance of the DataTable in CodeIgniter; it did not

I recently started using CodeIgniter and I'm having trouble getting the dataTable to work. Here's a snippet of my page: <table class="table table-striped table-bordered table-hover dataTables_default" id="dataTables-example"> ...

Performing a synchronous loop with Javascript promises

I've been struggling with a seemingly simple task that's been causing me immense frustration. Despite scouring the entire Internet, none of the solutions I found seem to directly address my specific issue. It all stems from a follow-up question r ...

Is there a way to combine multiple incoming WebRTC audio streams into one cohesive stream on a server?

I am currently working on developing an audio-conferencing application for the web that utilizes a WebSocket server to facilitate connections between users and enables streaming of audio. However, I am looking to enhance the system by transforming the serv ...

What could be causing the Or operator to malfunction within the ng-pattern attribute in AngularJS?

Currently, I am implementing the ng-pattern="/^(([A-Za-z]{0,5}) | ([0-9]{0,10}))$/". However, it seems like the input control is not accepting values such as "asd" or "09", despite my expectation that both should be valid inputs. Do you think the pipe sy ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

Changing the state using setState outside of the component does not trigger an update

My shop is situated within the store.js file like all the other Zustand stores: const retryStore = create(set => ({ retry_n: 0, setGRetry: (retry_n) => set(state => ({ ...state, retry_n, })), })); export { retryStore }; ...

Tips for showcasing JSON data within an array of objects

I'm trying to work with a JSON file that has the following data: {"name": "Mohamed"} In my JavaScript file, I want to read the value from an array structured like this: [{value: "name"}] Any suggestions on how I can acc ...

Certain public files in Express cannot be accessed locally

While running my Node.js application on localhost, I am able to access http://localhost:3000/css/dashboard.css without any issues. However, when attempting to access http://localhost:3000/css/logo.png for a logo image in the same directory, all I receive i ...

ExpressJS, defining routes, locating controllers, and documenting APIs

Utilizing expressJS 4.X and nodeJS 6.x In the past, I was defining my routes in this manner : /** * @api {get} /users/:userId Get a user * @apiName GetUser * @apiGroup User * * @apiParam {Integer} userId Users unique ID. * * @apiSuccess (Success 2 ...

What is the best way to send JSON data to a code behind method instead of a Webmethod?

I have a dilemma with handling JSON data in my code behind to bind it to an obout grid. While I am aware of passing data using the <WebMethod>, I've encountered limitations as the method is static, making it difficult to bind the data to any gri ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

Guide on making a persistent sidebar using CSS and JavaScript

I'm in the process of developing a website that features a main content area and a sidebar, similar to what you see on Stack Overflow. The challenge I am facing is figuring out how to make the sidebar remain visible as a user scrolls down the page. T ...

Is there a way to alter visibility once a radio button has been selected?

I have a shape resembling a cube with 4 faces, all of which are currently visible. However, I would like to hide the other 3 faces when one face is showing. For example: I attempted setting the opacity of the other cube sides to 0 when the first radio but ...

Use Entity Objects instead of Strings in your Ajax requests for improved data handling

As I work on developing a web portal with Freemarker(FTL) as the front end technology, my project revolves around a single FTL page that utilizes a wizard to manage various user requests. The back end is structured using the Spring MVC pattern, where contr ...

Filtering Sails.js query model based on a collection attribute

Imagine I have these models set up in Sails.js v0.10: Person.js module.exports = { attributes: { name: 'string', books: { collection: 'book', via: 'person' } } }; Book.js module.exports = { ...

Items in a pair of distinct columns

I want to enhance a picture by adding three paragraphs on the left-hand side. Below is my HTML code: <md-toolbar layout-align="center center"> <h3>Traffic Light Component</h3> </md-toolbar> <md-grid-list md-cols ...