Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object.

var old = {account: "100000", address: {city: "LONDON", companyName: "Test IQUE", country: "UK", postalCode: "SW1A 2AA",}, meterName: "DM9"}

This method worked fine for me when dealing with a smaller dataset

var new = [{   
              'account' : "100000",                         
              'address' : "LONDON, UK"
              'companyName' : "Test IQUE",
              'postalCode' : "SW1A 2AA",   
              'meterName' : "DM90"
           },
           {   
              'account' : "1000001",                         
              'address' : "LONDON, UK"
              'companyName' : "Test IQUE",
              'postalCode' : "SW1A 2AA",   
              'meterName' : "DM90"
           }];

Essentially, I am seeking a way to serialize my nested address objects and combine them into one. Since the structure of each object remains consistent, I am considering utilizing a forEach loop to merge the values of the addresses.

Answer №1

Want to extract a complete address string from an address object? Try out this snippet of code:

'fullAddress': Object.values($scope.userDetails.address).join(', ');

By using the Object.values() function, you can transform your address object into an array.

The .join method will merge all the elements of this array into a single string. These elements will be linked together by a specified separator (, in this situation).

Answer №2

If you need to utilize the lodash library, you can refer to their documentation on the assignIn method here: https://lodash.com/docs/4.17.15#assignIn

For more information, see:

_.assign(object, [sources])

function Foo() {
    this.a = 1;
}

function Bar() {
    this.c = 3;
}

Foo.prototype.b = 2;
Bar.prototype.d = 4;

_.assign({ 'a': 0 }, new Foo, new Bar);
// => { 'a': 1, 'c': 3 }

Additionally, you may also want to explore the mergeWith method in lodash:

function customizer(objValue, srcValue) {
    if (_.isArray(objValue)) {
        return objValue.concat(srcValue);
    }
}
 
var object = { 'a': [1], 'b': [2] };
var other = { 'a': [3], 'b': [4] };
 
_.mergeWith(object, other, customizer);
// => { 'a': [1, 3], 'b': [2, 4] }

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

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

The removal of classList.remove() only eliminates the class itself, not its contents

My goal is to add one class and remove another class when the start quiz button is clicked. While the 'info_box' class is successfully added, the 'start_btn' class does not get removed; it just changes position (from flex to no flex). T ...

What is the best way to stream an app's data directly to a browser in real time?

My node application is currently able to read a stream from a Kafka producer and display it in real time using console.log. However, I would like to update my web application with the same real-time functionality. How can I achieve this? I typically start ...

Disabling the global ajax datatype causes issues with Rails remote links

I have successfully developed a rails application that submits a form remotely and then displays form validation errors if the validation process fails. The form itself is working perfectly. However, I've come across an issue where the way I've ...

Is it possible to refresh AdSense banner when the router changes?

Is there a way to reload the AdSense banner ads when the router changes? I've been encountering issues trying to re-add the script and HTML properly. Any guidance on how this should be done would be greatly appreciated... This is just a test for one ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

Use either lodash or a for loop to organize a group of JSON objects

Here is the array I am working with: [ { corequisite: "", curriculumYr: "2017-2018", programCode: "ET" majorCode: "AET", prerequisites: "GMRC 101||Math 101" semester: "1st Term", year: "1st Year", subjectCode : "ENG ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

What is the best method for deleting the div with id "__next" in Next.js?

I'm currently working on a website using Next.js and I'm aiming to create a header with a position: sticky; effect. Nevertheless, Next.js automatically inserts a div with the attribute id="__next" at the top of my website without my co ...

Accessing the "this" object in Vue.js components

When executing console.log(this) in the doSomething method, it returns "null". I was expecting console.log(this.currentPage) to display "main", but unfortunately, the "this" object is null.. :( Is there a way to access the value of "main" for currentPage ...

What is the reason behind only seeing empty brackets [] when Array.prototype is displayed in

When looking at String.prototype, Object.prototype, and Boolean.prototype, we see that they all have a similar structure where the object {} is displayed. However, when it comes to Array.prototype, instead of displaying Array [], it outputs []. Why does ...

Encountering an error of "Cannot set headers after they are sent" when attempting to manage a user session during a test using the Chai request agent

We're currently facing a challenge with an error message stating Uncaught Error: Can't set headers after they are sent. when attempting to link a user sign-in to a test using chai-http. The test signs in a user already existing in the database v ...

What could be causing the AntiForgeryToken validation to fail while implementing AngularJS in an ASP.NET MVC application?

I am encountering a problem with passing the correct AntiForgeryToken when using AngularJS $http service in an ASP.NET MVC application. Here are the solutions I have attempted: Setting HTTP Request headers with an httpInterceptor app.factory('ht ...

I successfully merged two arrays (decks of cards) without using recursion, but I'm curious to understand where I went wrong with the recursive approach

Currently, I am working on a function that shuffles two arrays together using recursion. The goal is to combine the top and bottom halves of a deck of cards into a single array with elements interleaved. For example: The first element should come from the ...

There is a SyntaxError due to an unexpected token "o" in the JSON data. It is not a valid JSON format

This code is designed to check an XML file to see if the email or login inputted by a user is already in use, and then provide a JSON response. The AJAX code for this functionality is as follows: $.ajax({ type: 'post', dat ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

Regular expression for matching zero's following a decimal

I'm currently working on a regex method to validate decimals that only allow 2 numbers after the decimal point. For example, it should return true for 1.00 and false for 1.000, which it currently does. However, I also want it to return false for value ...

I developed a digital Magic 8 Ball program, but unfortunately, it's only providing me with one response

I'm currently working on a Discord Bot for my friends and myself. One of the scripts I've created is an 8Ball script, but it's only giving me one answer. Here's the code snippet for my variable: var rand = ['Yes', 'No&apo ...