What are the differences between JSON and JavaScript object? [duplicate]

First you should know what JSON is: It is language agnostic data-interchange format. The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them. For example, in JSON all keys must be quoted, while in object literals this is not necessary: // JSON: { “foo”: “bar” } // … Read more

JavaScript, elegant way to check nested object properties for null/undefined [duplicate]

You can use an utility function like this: get = function(obj, key) { return key.split(“.”).reduce(function(o, x) { return (typeof o == “undefined” || o === null) ? o : o[x]; }, obj); } Usage: get(user, ‘loc.lat’) // 50 get(user, ‘loc.foo.bar’) // undefined Or, to check only if a property exists, without getting its value: has … Read more

Number of elements in a javascript object

Although JS implementations might keep track of such a value internally, there’s no standard way to get it. In the past, Mozilla’s Javascript variant exposed the non-standard __count__, but it has been removed with version 1.8.5. For cross-browser scripting you’re stuck with explicitly iterating over the properties and checking hasOwnProperty(): function countProperties(obj) { var count … Read more

Create object from array

Simply const obj = {}; for (const key of yourArray) { obj[key] = whatever; } or if you prefer “functional” style: const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {}); using the modern object spread operator: const obj = yourArray.reduce((o, key) => ({ …o, [key]: whatever}), {}) Example: [ { id: 10, color: “red” … Read more

Is Chrome’s JavaScript console lazy about evaluating objects?

Thanks for the comment, tec. I was able to find an existing unconfirmed Webkit bug that explains this issue: https://bugs.webkit.org/show_bug.cgi?id=35801 (EDIT: now fixed!) There appears to be some debate regarding just how much of a bug it is and whether it’s fixable. It does seem like bad behavior to me. It was especially troubling to … Read more

Converting JavaScript object with numeric keys into array

It’s actually very straight forward with jQuery’s $.map var arr = $.map(obj, function(el) { return el }); FIDDLE and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map var arr = Object.keys(obj).map(function(k) { return obj[k] }); FIDDLE That’s assuming it’s already parsed as … Read more