Last active
March 16, 2023 11:28
-
-
Save arihantverma/8625a55420f5d66ba9388828a4a83ec4 to your computer and use it in GitHub Desktop.
Way to change a deep key (node) 's value in JSON using JSON.stringify's replacer function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://replit.com/@arihantverma1/JSON-stringify-deeply-nested-node-value-change?v=1 | |
const util = require('util') | |
const data = { | |
widgets: [ | |
{ | |
type: "performance", | |
data: { | |
progress_bars: [ | |
{ | |
merge_target: { | |
id: "1", | |
data: "one" | |
}, | |
}, | |
{ | |
merge_target: { | |
id: "2", | |
data: "two" | |
} | |
} | |
] | |
} | |
} | |
] | |
} | |
const sliceData = { | |
widgets: [ | |
{ | |
type: "performance", | |
data: { | |
progress_bars: [ | |
{ | |
merge_target: { | |
id: "1", | |
data: "hundred" | |
} | |
} | |
] | |
} | |
} | |
] | |
} | |
const sliceMergeData = findAllMergeIdsAndValues(sliceData) | |
var result = JSON.parse(findAndReplaceSliceMergeValues(data, sliceMergeData)) | |
console.info(sliceMergeData) | |
console.log(util.inspect(result, false, null, true /* enable colors */)) | |
function findAndReplaceSliceMergeValues(entireObj, slideMergeData) { | |
return JSON.stringify(entireObj, (key, nestedValue) => { | |
if (key === 'merge_target') { | |
const sliceDataSlice = slideMergeData.find(el => el.id === nestedValue.id) | |
const sliceDataValue = sliceDataSlice?.data | |
return sliceDataSlice ?? nestedValue | |
} | |
return nestedValue | |
}); | |
}; | |
function findAllMergeIdsAndValues(obj) { | |
let arr = [] | |
JSON.stringify(obj, (key, value) => { | |
if (key === "merge_target") { | |
arr.push({ id: value.id, data: value.data }) | |
} | |
return value | |
}) | |
return arr | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment