Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@heruan
Created May 29, 2015 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heruan/e42e05e1f52dd0fed9b9 to your computer and use it in GitHub Desktop.
Save heruan/e42e05e1f52dd0fed9b9 to your computer and use it in GitHub Desktop.
Mapping JSON parsed object instances
[
{
"name": "John",
"age": 20
},
{
"name": "Jack",
"age": 28
}
]
{
"id": 1234,
"assignee": {
"name": "Jack",
"age": 28
},
"comments": [
{
"text": "A comment.",
"author": {
"name": "Jack",
"age": 28
}
},
{
"text": "Another comment.",
"author": {
"name": "John",
"age": 20
}
}
]
}
var fs = require('fs');
var map = new Map();
var reviver = function(k, v) {
if (v === null || Array.isArray(v)) return v;
if (typeof v !== 'object') return v;
var key = JSON.stringify(v);
if (map.has(key)) {
return map.get(key);
}
map.set(key, v);
return v;
};
var arr = JSON.parse(fs.readFileSync("arr.json"), reviver);
var job = JSON.parse(fs.readFileSync("job1234.json"), reviver);
console.log(arr.indexOf(job.assignee)); // 1 => correct!
console.log(Object.is(job.assignee, job.comments[0].author)); // true => correct!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment