Skip to content

Instantly share code, notes, and snippets.

@manuc66
Last active February 1, 2018 13:46
Show Gist options
  • Save manuc66/aa39a197626d1aad42f50a7b520d7599 to your computer and use it in GitHub Desktop.
Save manuc66/aa39a197626d1aad42f50a7b520d7599 to your computer and use it in GitHub Desktop.
merge package.json helper
const fs = require("fs");
var a = JSON.parse(fs.readFileSync('p1.json', "utf8"));
var b = JSON.parse(fs.readFileSync('p2.json', "utf8"));
var dst = {};
function merge(destination, source, key) {
if (key === undefined) {
Object.keys(source).forEach(k => merge(destination, source, k));
}
else if (source[key] instanceof Object) {
if (destination[key] === undefined) {
destination[key] = {}
}
Object.keys(source[key]).forEach(k => merge(destination[key], source[key], k));
}
else {
if (destination[key] === undefined) {
destination[key] = [source[key]]
}
else if (!destination[key].includes(source[key])) {
destination[key].push(source[key])
}
}
}
merge(dst, a)
merge(dst, b)
console.log(dst)
var result = {};
function simplify(target, source) {
Object.keys(source).forEach(k => {
if (!(source[k] instanceof Array)) {
target[k] = {}
simplify(target[k], source[k])
}
else {
if (source[k].length === 1) {
target[k] = source[k][0]
}
else {
target[k] = source[k]
}
}
})
}
simplify(result, dst)
console.log(result)
{
"name": "my-package",
"dependencies": {
"babel": "^5.4.1",
"eslint": "^0.22.1"
}
}
{
"name": "my-package",
"dependencies": {
"babel": "^5.2.2",
"lodash": "^3.2.5"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment