What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects

var obj1={
 "name":"mayur",
  "age":23
}
var obj2={
    "name":"keyur",
    "age":29,
    "limit":54,
    "surname":"godhani"
}

//I am familiar with one approach

var j1 = {name: 'Varun', age: 24};
var j2 = {code: 'NodeJS',name:'mayur', alter: 'C++'}

for (var key in j1) {
    if(j2[key])
        j1[key] = j2[key];
}

console.log(j1);

//However, I desire to do it using lodash or in just one line of code

//--> The expected results should be as follows

var obj1={
    "name":"keyur",
    "age":29
}

Answer №1

You can utilize Lodash's `assign` method to add properties to an object and the `pick` method to select specific properties from `obj2` that are also present in obj1.

var obj1 = {
  "name": "mayur",
  "age": 23
}

var obj2 = {
  "name": "keyur",
  "age": 29,
  "limit": 54,
  "surname": "godhani"
}

var result = _.assign(obj1, _.pick(obj2, _.keys(obj1)))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Answer №2

Here is a suggestion for achieving this in just one line:

let obj1 = {name: 'Sara', age: 30};
let obj2 = {role: 'Developer', name:'Alex', skill: 'Python'}
Object.keys(obj1).map(key=>  obj1[key] = obj2[key] ?  obj2[key]: obj1[key])
console.log(obj1);

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

Customizing the width of the JQuery $ui.progressbar by overriding its properties

After spending some time, I successfully overrode the function that controls the width of the progress bar element in the jQuery UI widget version 1.12.1 from September 14, 2016. Initially, I needed the progress bar to completely fill a column in a table. ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

What is the method to implement foreach within a Vue select component?

Is there a way to utilize a Vue loop within a select box in order to achieve the following category and subcategory options layout: +news -sport -international +blog In PHP, I can accomplish this like so: @foreach($categories as $cat ...

Show various Bootstrap Alert Messages based on the type of error detected?

Trying to figure out how best to explain this, here it goes! I am working on a website and I want to incorporate alert messages. Check out some examples here. Depending on the form inputs, I need different alerts to be displayed. PHP will validate the in ...

Utilize the client's IP address as a cookie in order to recognize return visits and showcase a special message following the initial visit

First of all, a big thank you to anyone who can help resolve this issue. I apologize if this has been asked before (I couldn't find it anywhere, so I decided to post a new question). The main problem I am facing is getting my webpage to show an alert ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Unable to retrieve data from AJAX request in the AJAX success function

I've seen this question asked multiple times and I've gone through several answers regarding callbacks, but I'm still struggling to understand how to apply it to my specific situation. I have an ajax function that is being called from the su ...

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

How can I eliminate the CSS value that was inherited?

Looking for a way to eliminate the effect of an inherited CSS property with Jquery. .class1 #id1 div.class2 input.class-input{ border-color: #bbb3b9 #c7c1c6 #c7c1c6; } Can someone explain how to delete this "border-color"? Thanks. ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

How do you write functions in ES6?

When attempting to access my namespaced store in Vue, I encountered an issue: methods: { ...mapActions('Modal', [ 'toggleActive', ]), close: () => { this.toggleActive(); } This resulted in the follow ...

Issue with ESlint global installation in macOS root terminal

Having trouble installing ESlint globally on my Mac running Mojave 10.14.6. Every time I try to run 'npm install -g eslint' I keep encountering this error: Your operating system has rejected the operation. npm ERR! It seems that you lack the nec ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

What are some ways to ensure that the promise from postgres is fulfilled before moving forward with my code execution?

I am currently developing a Node-js application that requires retrieving information from the database before making another database call. However, I am facing an issue where the first check is not always resolved before proceeding to the next step. I hav ...

Scroll through the menu with ease

I am facing an issue with my menu that has 2 levels. Whenever I try to scroll down, I want the position of the Logo to change to the bottom of the menu smoothly. However, during scrolling, there is a noticeable shake in the menu movement which makes it app ...

What is the best way to reposition an element to the end of its flexbox container?

I have a flexbox-container that contains multiple details-elements with flex-wrap behavior. My goal is to have a details-element move below the other elements within the container when it is opened. For example, I want it to go from this initial layout: ...

What is the best way to show toast notifications for various selections in a dropdown menu?

I have a dropdown menu labeled "FavoriteFoods" that includes options such as "Pizza," "Sushi," "Burgers," and "Biryani." When one of these food choices is selected from the dropdown, I would like a toast pop-up to appear with the message "Great choice!" ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...

Using Vue.js to dynamically calculate elapsed time

I am attempting to display the changing elapsed time from a specified start time <template> <div class="dashboard-editor-container"> <div class="wrapper__body"> <el-row :gutter="30"> <el-col v-fo ...