1

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

1

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

This answer doesn't give the desired result. The OP's required result indicates gf.last on first object ("john") should be replaced by the second object's gf.last property ("Anup") so that result gf.last should be "Anup", not "john"
1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.