Suraj Dalvi
Suraj Dalvi

Reputation: 1078

Merge two JSON Object in Node .js

I have two json object and i want to merge it. it means ifsame key is there then want to overwrite it. How I can do it using node.js. kindly check below sample:

first object

{
"title": "Test",
"url": "/test",
"gf": {
    "name": "kim",
    "last": "john"
},
"created_at": "2021-09-08T18:40:50.152Z",
"updated_at": "2021-09-08T18:54:36.387Z",
"version": 9
}

Second Object

{
"gf": {
    "last": "Anup"
},
"__originalParams": {
    "gf": {
        "last": "Anup"
    }
}
}

Required Result

{
"title": "Test",
"url": "/test",
"gf": {
    "name": "kim",
    "last": "Anup"
},
"created_at": "2021-09-08T18:40:50.152Z",
"updated_at": "2021-09-08T18:54:36.387Z",
"version": 9,
"__originalParams": {
    "gf": {
        "last": "Anup"
    }
}
}

How I get this result using node.js . It is just a sample I have complex JSON structure too. is any direct option present in Lodash or Ramda for this. Kindly help me here

Upvotes: 1

Views: 3962

Answers (3)

Timur
Timur

Reputation: 2287

You can use lodash merge or the deepmerge package:

var lhs = {
  "title": "Test",
  "url": "/test",
  "gf": {
    "name": "kim",
    "last": "john"
  },
  "created_at": "2021-09-08T18:40:50.152Z",
  "updated_at": "2021-09-08T18:54:36.387Z",
  "version": 9
};

var rhs = {
  "gf": {
    "last": "Anup"
  },
  "__originalParams": {
    "gf": {
      "last": "Anup"
    }
  }
}

var ans = deepmerge(lhs, rhs)
var ans2 = _.merge(lhs, rhs)

console.log(ans)
console.log(ans2)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/umd.js"></script>

Upvotes: 1

LeeLenalee
LeeLenalee

Reputation: 31371

You can use Object.assign:

let obj1 = {
"gf": {
    "last": "Anup"
},
"__originalParams": {
    "gf": {
        "last": "Anup"
    }
}
};

let obj2 = {
"title": "Test",
"url": "/test",
"gf": {
    "name": "kim",
    "last": "john"
},
"created_at": "2021-09-08T18:40:50.152Z",
"updated_at": "2021-09-08T18:54:36.387Z",
"version": 9
};

let merged = Object.assign({}, obj1, obj2);

console.log(merged)

Upvotes: 1

Vishnu Vinod
Vishnu Vinod

Reputation: 765

You can use the JavaScript's Spread operator for this purpose. You can try,

let obj1 = {
    key: 'value'
    ...
}
let obj2 = {
    key: 'value'
    ...
}
console.log({ ...obj1, ...obj2 })

You will get the desired output by replacing the values of obj 1 by values of obj2

Upvotes: 2

Related Questions