Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active October 26, 2020 07:16
Show Gist options
  • Save jialinhuang00/521093519005a2c2c8c1274902d87842 to your computer and use it in GitHub Desktop.
Save jialinhuang00/521093519005a2c2c8c1274902d87842 to your computer and use it in GitHub Desktop.
nuance about javascript object
const obj = {
a: 32,
b: 32,
c: "Hello",
d: 128,
};
let total = 0;
Object.prototype.parentPro = 300;
function iterateToSum(obj) {
for (let key in obj) {
// if (typeof obj[key] === 'number') total += obj[key] // 492
if (typeof obj[key] === 'number' && obj.hasOwnProperty(key)) total += obj[key] //192
}
return total
}
var layeredObj = { a: { b: "c" }, x: 4 }
var copiedObj = Object.assign({}, layeredObj)
// change nested property: a
layeredObj.a.b = "d"
// change level 0 properties: g, x
layeredObj.g = 5
layeredObj.x = 8
// support copiedObj to delete property x
const replacer = (k, v) => { if (k === 'x') { v = 6 } else return v };
console.log('ORIGIN: ', JSON.stringify(layeredObj, null, 2), '\n')
console.log('NEW: ', JSON.stringify(copiedObj, replacer, 2))
/*
ORIGIN: {
"a": {
"b": "d"
},
"g": 5,
"x": 8
}
NEW: {
"a": {
"b": "d"
},
"g": 2
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment