Substitute an item with another -JavaScript

While I understand this is a rather common question, my search through various sources has yielded answers that involve libraries, ES6, or methods not supported by native JavaScript. My goal is to simply replace one object with another based on a condition - no ES6, no clone, and no copy.

In the scenario below: I aim to extract values from subObj and replace them with the values in Obj1

For example, I want attributes "key2" and "key3" to be replaced with the values present in subObj.

Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
"key2" : {values:[91, 25, 44, 5995]},
"key3" : {values:[1, 24, 44, 595]},
"key4" : {values:[17, 28, 44, 559]}
}

subObj = {
**"key2" : {values:[3, 3, 3, 444]},** // add this one 
**"key3" : {values:[1, 0, 0, 0]}**
}

The desired output should look like:

Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
**"key2" :{ values:[3, 3, 3, 444]},**
**"key3" : {values:[1, 0, 0, 0]},**
"key4" : {values:[17, 28, 44, 559]}
}

Thus far, I have attempted the following code snippet:

  somefunc: function(condition) {

          if (condition) {
            Object.keys(Obj1).forEach(function(key) { Obj[key] = Obj1[key]});
            return Obj1;
          }
          return Obj;
        },

However, this method has not produced the expected results. Any assistance would be greatly appreciated. Thank you!

Answer №1

function combineObjects(object1, subObject) {
    const mergedResult = {};

    Object.keys(object1).forEach((key) => {
        mergedResult[key] = object1[key]
    })

    Object.keys(subObject).forEach((k) => {
        if(mergedResult[k]){
            console.log('Updated value')
            mergedResult[k] = subObject[k]
        } else {
            console.log("Added new value")
            mergedResult[k] = subObject[k]
        }
    })

    console.log(mergedResult)
    return mergedResult
}

combineObjects(object1, subObject)

Answer №2

If you need to merge objects in JavaScript, you can utilize the Object.assign() method.

// ...

if (condition) {
    return Object.assign(Obj1, subObj);
}

// ...

Answer №3

Learn about the effective use of the spread operator in JavaScript

const Obj1 = {
"key1" : {values:[1, 2, 44, 505]},
"key2" : {values:[91, 25, 44, 5995]},
"key3" : {values:[1, 24, 44, 595]},
"key4" : {values:[17, 28, 44, 559]}
}

const subObj = {

"key2" : {values:[3, 3, 3, 444]},
"key3" : {values:[1, 0, 0, 0]}

}

console.log({ ...Obj1, ...subObj });

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

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over: <div id="locationmap"> <a class="linkhide" id="link1" href="#">Occupier 1</a> <a class="linkhide" id ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

Resolution for Vue3: Understanding why a component instance's template ref cannot locate a defined function

LoginInfo.vue <script setup lang="ts"> import { rules } from './config/AccountConfig' import { reactive } from 'vue' import { ref } from 'vue'; import { ElForm } from 'element-plus'; const info = reac ...

When implementing multer in an express application, I encountered an issue where req.files appeared empty

Currently, I am facing some issues while attempting to upload various file types to the server using multer in an express application. Whenever I make the request, the server responds with a TypeError: req.files is not iterable. Upon investigation, I notic ...

What is the technique for adjusting the background while rotating the corner?

Is it possible to position a background image in the corner while rotating another image? rotate: $('#ship').css({ transform: 'rotate(' + corner + 'deg)' }); } move background: starx[i]=starx[i]+... s ...

Having difficulty choosing an item from a personalized autocomplete search bar in my Vue.js/Vuetify.js project

NOTE: I have opted not to use v-autocomplete or v-combobox due to their limitations in meeting my specific requirements. I'm facing difficulties while setting up an autocomplete search bar. The search functionality works perfectly except for one mino ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

The jQuery selectors are not able to identify any dynamically generated HTML input elements

After successfully injecting HTML code into the DOM using Ajax, I encountered an issue where my jQuery selector was not working for a specific HTML input element. For example, when attempting to use the following jQuery code: $("input[id*='cb_Compare ...

I am looking to transfer the value of one textbox to another textbox within a dynamic creation of textboxes using JavaScript

var room = 1; function add_fields() { room=$('#row_count').val()-1; room++; var objTo = document.getElementById('education_fields'); var divtest = document.createElement("div"); divtest.setAttribute("class", "form- ...

Send a PHP object to JavaScript using AJAX

I have a PHP script that successfully uploads a video to the Microsoft Azure service using an API. The API returns a StdObject file, which I then want to send back to JavaScript via AJAX. However, when I try to access the "asset" object in JavaScript, it a ...

Oops: Looks like there is already a request for 'PUBLIC_requestAccounts' pending from http://localhost:3000. Just hold tight for now

There comes a moment when an unexpected error arises and fails to establish a connection with your wallet. if (window.ethereum) { console.log("11") const connect = async () => { const account = await window.ethereum.request({ ...

Is it possible to apply several 'where' condition in pg-promise?

I am currently using pg-promise in combination with express 4 on node 8.2.0. I am trying to concatenate the where condition. However, I have been unable to find a way to achieve this. Can you please assist me? This is what I am aiming for. let ids = [10 ...

Is Javascript Functioning Properly?

Similar Question: How do I determine if JavaScript is turned off? Can we identify whether javascript has been disabled and then redirect to a different page? I am currently working on a project using JSPs, where I have integrated various advanced java ...

Vue encountering RangeError due to string length inconsistency in specific environments only

My Vue component is currently live in production within a WordPress theme, but I am encountering an error: jquery.min.js:2 Uncaught RangeError: Invalid string length at repeat$1 (vue.js:11398) at generateCodeFrame (vue.js:11380) at vue.js:1146 ...

How do I retrieve my compiled template from a directive in Angular?

Having a directive structured as follows: return { scope:{ divid: '@' }, template: '<div id="{{divid}}"></div>' } Here is an example instance: <direct divid="some-id"></direct> The goal is to execut ...

Learn how to retrieve data using the $.ajax() function in jQuery and effectively showcase it on your HTML page

Can someone assist me with extracting data from https://jsonplaceholder.typicode.com/? Below is the AJAX call I'm using: $.ajax({ url: root + '/posts/', data: { userId: 1 }, type: "GET", dataType: "json", success: function(data) { ...

Is it possible to disable the "super must be called before accessing this keyword" rule in babelify?

My current setup involves using babelify 7.2.0 with Gulp, but I've encountered an error when working with the following code snippet: class One {} class Two extends One { constructor() { this.name = 'John'; } } The issue at hand i ...

Default value for the href property in NextJS Link is provided

Is there a default href value for Next/Link that can be used, similar to the way it is done in plain HTML like this: <a href='#' ></a> I attempted to do this with Link, but it resulted in the page reloading. Leaving it empty caused a ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...