Skip to content

Instantly share code, notes, and snippets.

@heruan
Created May 29, 2015
Embed
What would you like to do?
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