Created
May 29, 2015 15:03
-
-
Save heruan/e42e05e1f52dd0fed9b9 to your computer and use it in GitHub Desktop.
Mapping JSON parsed object instances
This file contains 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
[ | |
{ | |
"name": "John", | |
"age": 20 | |
}, | |
{ | |
"name": "Jack", | |
"age": 28 | |
} | |
] |
This file contains 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
{ | |
"id": 1234, | |
"assignee": { | |
"name": "Jack", | |
"age": 28 | |
}, | |
"comments": [ | |
{ | |
"text": "A comment.", | |
"author": { | |
"name": "Jack", | |
"age": 28 | |
} | |
}, | |
{ | |
"text": "Another comment.", | |
"author": { | |
"name": "John", | |
"age": 20 | |
} | |
} | |
] | |
} |
This file contains 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
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