Assign the value of one variable to another variable using the same keys

I'm facing a scenario where I have two arrays named array1 and array2. My goal is to transfer the values from array2 into array1 for the properties that exist in array1, while keeping the default values for any properties that are not present.

One approach I considered was iterating through the length of the arrays to set values for matching properties. However, due to the extensive size of my actual array (the example provided here is simplified), this method is not efficient.

I am seeking an alternative solution that does not involve iteration.

var array1=[
    {
        "name": "a",
        "value": 0,
        "level": [
            {
                "name": "a1",
                "value": 0
            },
            {
                "name": "a2",
                "value": 0
            }
        ]
    },
    {
        "name": "b",
        "value": 0,
        "level": [
            {
                "name": "b1",
                "value": 0
            },
            {
                "name": "b2",
                "value": 0
            }
        ]
    },
    {
        "name": "c",
        "value": 0,
        "level": [
            {
                "name": "c1",
                "value": 0
            },
            {
                "name": "c2",
                "value": 0
            }
        ]
    }
]



var array2=[
    {
        "name": "a",
        "value": 1,
        "level": [
            {
                "name": "a1",
                "value": 1
            },
            {
                "name": "a2",
                "value": 0
            }
        ]
    },
    {
        "name": "b",
        "value": 1,
        "level": [
            {
                "name": "b1",
                "value": 0
            },
            {
                "name": "b2",
                "value": 1
            }
        ]
    }    
]

The desired output should resemble:

var final_array=[
    {
        "name": "a",
        "value": 1,
        "level": [
            {
                "name": "a1",
                "value": 1
            },
            {
                "name": "a2",
                "value": 0
            }
        ]
    },
    {
        "name": "b",
        "value": 1,
        "level": [
            {
                "name": "b1",
                "value": 0
            },
            {
                "name": "b2",
                "value": 1
            }
        ]
    },
    {
        "name": "c",
        "value": 0,
        "level": [
            {
                "name": "c1",
                "value": 0
            },
            {
                "name": "c2",
                "value": 0
            }
        ]
    }
]

Answer №1

Using a recursive approach, this solution involves two iterators - one for arrays called iterateA and another for objects called iterateO. The thisArg is utilized to reference json2 within the function.

Essentially, both callbacks iterate through the items or keys, checking if this is set and if the current item is present in this. If not, the function simply returns.

The process continues straightforwardly by iterating over keys when an object is encountered, or over the array when an array is found.

Only when k === 'value', the value of this[k] is assigned to o[k].

var json1 = [{ "name": "a", "value": 0, "level": [{ "name": "a1", "value": 0 }, { "name": "a2", "value": 0 }] }, { "name": "b", "value": 0, "level": [{ "name": "b1", "value": 0 }, { "name": "b2", "value": 0 }] }, { "name": "c", "value": 0, "level": [{ "name": "c1", "value": 0 }, { "name": "c2", "value": 0 }] }],
    json2 = [{ "name": "a", "value": 1, "level": [{ "name": "a1", "value": 1 }, { "name": "a2", "value": 0 }] }, { "name": "b", "value": 1, "level": [{ "name": "b1", "value": 0 }, { "name": "b2", "value": 1 }] }];

function iterateO(o) {
    return function (k) {
        if (!this || !(k in this)) {
            return;
        }
        if (typeof o[k] === 'object') {
            Object.keys(o[k]).forEach(iterateO(o[k]), this[k]);
            return;
        }
        if (Array.isArray(o[k])) {
            o[k].forEach(iterateA, this[k]);
            return;
        }
        if (k === 'value') {
            o[k] = this[k];
        }
    };
}

function iterateA(a, i, aa) {
    if (!this || !(i in this)) {
        return;
    }
    if (typeof a === 'object') {
        Object.keys(a).forEach(iterateO(a), this[i]);
        return;
    }
    if (Array.isArray(a)) {
        a.forEach(iterateA, this[i]);
        return;
    }
}

json1.forEach(iterateA, json2);
document.write('<pre>' + JSON.stringify(json1, 0, 4) + '</pre>');

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

Activate the zoom feature in jquery mobile

I am looking to implement the standard zooming effect in jquery mobile for my iOS iPhone app using jqm 1.3.2. After attempting the following: <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-s ...

Viewing Server Logs in a Discord Channel

My gaming server stores logs in .txt format, and I'm looking for a way to automatically send updates to a Discord channel whenever there is new log data. I am currently developing a Discord bot using Node.js. Does anyone have any suggestions on how I ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

Angular dropdown menu with 2 options

Looking to implement a select box with various price ranges to choose from. For example: - 0 to $2,000 - $2,000 to $3,500 - $3,500 to $5,000 - $5,000 to $7,500 - $7,500 to $10,000 - $10,000 Once a user selects an option, I want to automatically set the ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

steps to receive an event within an AngularJS function

I'm encountering an issue with the event display in this code. <div class="div1" ng-click="displayinfo(event)"> sadfasf </div> $scope.displayinfo = function(event) { alert(event); } Does anyone have a solution for this problem? ...

The concept of undefined in JavaScript when an if condition is applied

In Node.js, there is a method used to handle API requests. An unusual behavior occurs when dealing with req.query.foo - even if it has a value defined, it becomes undefined when used in an if condition as shown below. Additionally, another req.query.foo ...

The problem with the Next.js 14 generateStaticParamsparams parameter is that it is currently

I'm using this documentation as a reference to extract parameters from the URL in my generateStaticParams function: https://nextjs.org/docs/app/api-reference/functions/generate-static-params#generate-params-from-the-bottom-up This is the route I am w ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

Using a navigation bar as a structural component in React

I have a new app in development that features a search bar on every page as part of the layout. When a user conducts a search, the results are displayed and they can click on a result to view more details in a separate component. My main question is regar ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Prevent removal of item from ngRepeat

Seeking a method to capture the removal of an element within an ngRepeat loop. My goal is to incorporate animations during this process. While handling the addition of elements can be done using the 'link' event, I am uncertain how to intervene d ...

Utilizing Header and Footer Components in React JS

I'm new to Reactjs(Nextjs) and I am looking to create a "header" and "footer" file that can be used on all pages. I would like to know the best approach to achieve this. Should I create a "Layout.js" file and then call the Header within it? Or should ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

A comparison of Vue's import paths: exploring the variations

Exploring the world of Vue has been exciting but I'm a bit puzzled by the syntax used for importing different libraries. Take, for instance, this import statement: import Vue from 'vue'; import axios from 'axios'; Where do these r ...

Steps for identifying the file format of a document with JavaScript

Can someone assist me in determining a file type using JavaScript within the context of this HTML code? <div class="indi-download"> <div class="pull-left"> <h6 class="file-format">%file_display_name%</h6> </div> <div c ...

Get rid of numerous div elements in a React.js application with the help of a Remove button

I need help figuring out how to efficiently remove the multiple div's that are generated using the add button. I am struggling to grasp how to pass the parent div's id into the delete method from the child div. Additionally, I'm wondering if ...