简体   繁体   中英

How do i copy required values from one JSON object to another with lodash?

//I have two

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

//I know one way

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);

//But i want with lodash or in one line

//--> results should be like

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

With Lodash you can use assign to add to object and pick to pick properties from obj2 that exists 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> 

for one line try this,

 var j1 = {name: 'Varun', age: 24}; var j2 = {code: 'NodeJS',name:'mayur', alter: 'C++'} Object.keys(j1).map(a=> j1[a] = j2[a] ? j2[a]: j1[a]) console.log(j1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM