How to check if JavaScript object is JSON - javascript

I have a nested JSON object that I need to loop through, and the value of each key could be a String, JSON array or another JSON object. Depending on the type of object, I need to carry out different operations. Is there any way I can check the type of the object to see if it is a String, JSON object or JSON array?
I tried using typeof and instanceof but both didn't seem to work, as typeof will return an object for both JSON object and array, and instanceof gives an error when I do obj instanceof JSON.
To be more specific, after parsing the JSON into a JS object, is there any way I can check if it is a normal string, or an object with keys and values (from a JSON object), or an array (from a JSON array)?
For example:
JSON
var data = "{'hi':
{'hello':
['hi1','hi2']
},
'hey':'words'
}";
Sample JavaScript
var jsonObj = JSON.parse(data);
var path = ["hi","hello"];
function check(jsonObj, path) {
var parent = jsonObj;
for (var i = 0; i < path.length-1; i++) {
var key = path[i];
if (parent != undefined) {
parent = parent[key];
}
}
if (parent != undefined) {
var endLength = path.length - 1;
var child = parent[path[endLength]];
//if child is a string, add some text
//if child is an object, edit the key/value
//if child is an array, add a new element
//if child does not exist, add a new key/value
}
}
How do I carry out the object checking as shown above?

I'd check the constructor attribute.
e.g.
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;
function whatIsIt(object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
if (object.constructor === stringConstructor) {
return "String";
}
if (object.constructor === arrayConstructor) {
return "Array";
}
if (object.constructor === objectConstructor) {
return "Object";
}
{
return "don't know";
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
for (var i=0, len = testSubjects.length; i < len; i++) {
alert(whatIsIt(testSubjects[i]));
}
Edit: Added a null check and an undefined check.

You can use Array.isArray to check for arrays. Then typeof obj == 'string', and typeof obj == 'object'.
var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
if (Array.isArray(p)) return 'array';
else if (typeof p == 'string') return 'string';
else if (p != null && typeof p == 'object') return 'object';
else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));
's' is string'a' is array 'o' is object'i' is other

An JSON object is an object. To check whether a type is an object type, evaluate the constructor property.
function isObject(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Object;
}
The same applies to all other types:
function isArray(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Array;
}
function isBoolean(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Boolean;
}
function isFunction(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Function;
}
function isNumber(obj)
{
return obj !== undefined && obj !== null && obj.constructor == Number;
}
function isString(obj)
{
return obj !== undefined && obj !== null && obj.constructor == String;
}
function isInstanced(obj)
{
if(obj === undefined || obj === null) { return false; }
if(isArray(obj)) { return false; }
if(isBoolean(obj)) { return false; }
if(isFunction(obj)) { return false; }
if(isNumber(obj)) { return false; }
if(isObject(obj)) { return false; }
if(isString(obj)) { return false; }
return true;
}

you can also try to parse the data and then check if you got object:
try {
var testIfJson = JSON.parse(data);
if (typeof testIfJson == "object"){
//Json
} else {
//Not Json
}
}
catch {
return false;
}

If you are trying to check the type of an object after you parse a JSON string, I suggest checking the constructor attribute:
obj.constructor == Array || obj.constructor == String || obj.constructor == Object
This will be a much faster check than typeof or instanceof.
If a JSON library does not return objects constructed with these functions, I would be very suspiciouse of it.

The answer by #PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof
function isJson(obj) {
var t = typeof obj;
return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}

You could make your own constructor for JSON parsing:
var JSONObj = function(obj) { $.extend(this, JSON.parse(obj)); }
var test = new JSONObj('{"a": "apple"}');
//{a: "apple"}
Then check instanceof to see if it needed parsing originally
test instanceof JSONObj

I wrote an npm module to solve this problem. It's available here:
object-types: a module for finding what literal types underly objects
Install
npm install --save object-types
Usage
const objectTypes = require('object-types');
objectTypes({});
//=> 'object'
objectTypes([]);
//=> 'array'
objectTypes(new Object(true));
//=> 'boolean'
Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types

Why not check Number - a bit shorter and works in IE/Chrome/FF/node.js
function whatIsIt(object) {
if (object === null) {
return "null";
}
else if (object === undefined) {
return "undefined";
}
if (object.constructor.name) {
return object.constructor.name;
}
else { // last chance 4 IE: "\nfunction Number() {\n [native code]\n}\n" / node.js: "function String() { [native code] }"
var name = object.constructor.toString().split(' ');
if (name && name.length > 1) {
name = name[1];
return name.substr(0, name.indexOf('('));
}
else { // unreachable now(?)
return "don't know";
}
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
// Test all options
console.log(whatIsIt(null));
console.log(whatIsIt());
for (var i=0, len = testSubjects.length; i < len; i++) {
console.log(whatIsIt(testSubjects[i]));
}

I combine the typeof operator with a check of the constructor attribute (by Peter):
var typeOf = function(object) {
var firstShot = typeof object;
if (firstShot !== 'object') {
return firstShot;
}
else if (object.constructor === [].constructor) {
return 'array';
}
else if (object.constructor === {}.constructor) {
return 'object';
}
else if (object === null) {
return 'null';
}
else {
return 'don\'t know';
}
}
// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];
console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));
testSubjects.map(function(testSubject){
console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));
});
Result:
typeOf() input parameter
---------------------------
boolean true
boolean false
number 1
number 2.3
string "string"
array [4,5,6]
object {"foo":"bar"}
null null
undefined

I know this is a very old question with good answers. However, it seems that it's still possible to add my 2ยข to it.
Assuming that you're trying to test not a JSON object itself but a String that is formatted as a JSON (which seems to be the case in your var data), you could use the following function that returns a boolean (is or is not a 'JSON'):
function isJsonString( jsonString ) {
// This function below ('printError') can be used to print details about the error, if any.
// Please, refer to the original article (see the end of this post)
// for more details. I suppressed details to keep the code clean.
//
let printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
JSON.parse( jsonString );
return true; // It's a valid JSON format
} catch (e) {
return false; // It's not a valid JSON format
}
}
Here are some examples of using the function above:
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );
console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );
console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );
console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );
console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );
console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );
console.log('\n7 -----------------');
j = '[{"a":1, "b": 2}, {"c":3}]';
console.log( j, isJsonString(j) );
When you run the code above, you will get the following results:
1 -----------------
abc false
2 -----------------
{"abc": "def"} true
3 -----------------
{"abc": "def} false
4 -----------------
{} true
5 -----------------
[{}] true
6 -----------------
[{},] false
7 -----------------
[{"a":1, "b": 2}, {"c":3}] true
Please, try the snippet below and let us know if this works for you. :)
IMPORTANT: the function presented in this post was adapted from https://airbrake.io/blog/javascript-error-handling/syntaxerror-json-parse-bad-parsing where you can find more and interesting details about the JSON.parse() function.
function isJsonString( jsonString ) {
let printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
JSON.parse( jsonString );
return true; // It's a valid JSON format
} catch (e) {
return false; // It's not a valid JSON format
}
}
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );
console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );
console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );
console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );
console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );
console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );
console.log('\n7 -----------------');
j = '[{"a":1, "b": 2}, {"c":3}]';
console.log( j, isJsonString(j) );

Try, Catch block will help you to solve this
Make a function
function IsJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Example:
console.log(IsJson('abc')) // false
console.log(IsJson('[{"type":"email","detail":"john#example.com"}]')) // true

Try this
if ( typeof is_json != "function" )
function is_json( _obj )
{
var _has_keys = 0 ;
for( var _pr in _obj )
{
if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
{
_has_keys = 1 ;
break ;
}
}
return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}
It works for the example below
var _a = { "name" : "me",
"surname" : "I",
"nickname" : {
"first" : "wow",
"second" : "super",
"morelevel" : {
"3level1" : 1,
"3level2" : 2,
"3level3" : 3
}
}
} ;
var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;
console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );

Based on #Martin Wantke answer, but with some recommended improvements/adjusts...
// NOTE: Check JavaScript type. By Questor
function getJSType(valToChk) {
function isUndefined(valToChk) { return valToChk === undefined; }
function isNull(valToChk) { return valToChk === null; }
function isArray(valToChk) { return valToChk.constructor == Array; }
function isBoolean(valToChk) { return valToChk.constructor == Boolean; }
function isFunction(valToChk) { return valToChk.constructor == Function; }
function isNumber(valToChk) { return valToChk.constructor == Number; }
function isString(valToChk) { return valToChk.constructor == String; }
function isObject(valToChk) { return valToChk.constructor == Object; }
if(isUndefined(valToChk)) { return "undefined"; }
if(isNull(valToChk)) { return "null"; }
if(isArray(valToChk)) { return "array"; }
if(isBoolean(valToChk)) { return "boolean"; }
if(isFunction(valToChk)) { return "function"; }
if(isNumber(valToChk)) { return "number"; }
if(isString(valToChk)) { return "string"; }
if(isObject(valToChk)) { return "object"; }
}
NOTE: I found this approach very didactic, so I submitted this answer.

Peter's answer with an additional check! Of course, not 100% guaranteed!
var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
outPutValue = JSON.stringify(jsonToCheck);
try{
JSON.parse(outPutValue);
isJson = true;
}catch(err){
isJson = false;
}
}
if(isJson){
alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
alert("Is other!");
}

I have a pretty lazy answer to this, which will not throw an error if you try to parse a string/other values.
const checkForJson = (value) => {
if (typeof value !== "string") return false;
return value[0] === "{" && value[value.length - 1] === "}";
}
You can use this to check the value of your keys while you make some recursive func; sorry if this doesn't answer the question completely
Ofc this isn't the most elegant solution and will fail when a string actually starts with "{" and ends with "}" although those use cases would be rare, and if you really wanted, you can check for a presence of quotes or other nonsense... anyway, use at your own discretion.
TLDR: it's not bulletproof, but it's simple and works for the vast majority of use cases.

lodash is also the best bet to check these things.
function Foo() {
this.a = 1;
}
_.isPlainObject(new Foo);
// => false
_.isPlainObject([1, 2, 3]);
// => false
_.isPlainObject({ 'x': 0, 'y': 0 });
// => true
_.isPlainObject(Object.create(null));
// => true
https://www.npmjs.com/package/lodash
https://lodash.com/docs/#isPlainObject

Quickly check for a JSON structure using lodash-contrib:
const _ = require('lodash-contrib');
_.isJSON('{"car": "ferarri"}'); //true for stringified
_.isJSON({car: "ferarri"}); //true
Usage guide: this blog entry

try this dirty way
('' + obj).includes('{')

Related

All object property is not empty javascript

How to check the following object, make sure every property is not equal to undefined, null or empty string?
userObj = {
name: {
first: req.body.first,
last: req.body.last
},
location: {
city: req.body.city
},
phone: req.body.phone
}
I can check req.body one by one like if(req.body.first) but that's too tedious if I have many params.
You can simply use Array.prototype.some() method over Object.values() to implement this in a recursive way:
function isThereAnUndefinedValue(obj) {
return Object.values(obj).some(function(v) {
if (typeof v === 'object'){
if(v.length && v.length>0){
return v.some(function(el){
return (typeof el === "object") ? isThereAnUndefinedValue(el) : (el!==0 && el!==false) ? !el : false;
});
}
return isThereAnUndefinedValue(v);
}else {
console.log(v);
return (v!==0 && v!==false) ? !v : false;
}
});
}
In the following function we will:
Loop over our object values.
Check if the iterated value is an object we call the function recursively with this value.
Otherwise we will just check if this is a truthy value or not.
Demo:
This is a working Demo:
userObj = {
name: {
first: "req.body.first",
last: [5, 10, 0, 40]
},
location: {
city: "req.body.city"
},
phone: "req.body.phone"
}
function isThereAnUndefinedValue(obj) {
return Object.values(obj).some(function(v) {
if (typeof v === 'object'){
if(v.length && v.length>0){
return v.some(function(el){
return (typeof el === "object") ? isThereAnUndefinedValue(el) : (el!==0 && el!==false) ? !el : false;
});
}
return isThereAnUndefinedValue(v);
}else {
console.log(v);
return (v!==0 && v!==false) ? !v : false;
}
});
}
console.log(isThereAnUndefinedValue(userObj));
You will get a function that validates every object and its sub objects in a recursive way.
To check for truthy values (values other than false, '', 0, null, undefined):
const hasOnlyTruthyValues = obj => Object.values(obj).every(Boolean);
Example:
const hasOnlyTruthyValues = obj => Object.values(obj).every(Boolean);
const object = {
a: '12',
b: 12,
c: ''
};
console.log(hasOnlyTruthyValues(object));
The example you posted (if (res.body.first) ...) also checks for a truthy value. If you want to allow false and 0 (which are falsy, but you didn't mention them in your question), use:
const hasOnlyAllowedValues = obj => Object.values(obj).every(v => v || v === 0 || v === false);
you can create a simple validator for yourself like function below
var body = {
a: 1,
b: 3
};
var keys = ['a', 'b', 'c'];
function validate(body, keys) {
for (var i in keys) {
if (!body[keys[i]]) {
return false;
}
}
return true;
}
console.log(validate(body, keys));
you can use the following validator to check, it works for a nested object as well
function objectValidator(obj){
let ret = true;
for(property in obj){
//console.log(property, obj[property], typeof obj[property]);
if(typeof obj[property] == "object"){
if(obj[property] instanceof Array){
ret = (ret & true);
}
else if(obj[property] == null){
ret = false;
}
else{
ret = (ret & objectValidator(obj[property]));
}
}
else if(typeof obj[property] == "string"){
if(obj[property] == ""){
ret = false;
}
}
else if(typeof obj[property] == "undefined"){
ret = false;
}
}
return ret;
}
let a = {
b : 1,
c :{
d: 2,
e: [3, 4],
f : ""
}
}
console.log(objectValidator(a));
In your post you use:
if(req.body.first)
I don't know if you are checking req and body before hand, but this should be:
if ( typeof req == "object" && typeof req.body == "object"
&& req.body.first ) {
That is a safer way to check before use.
Or, if you want to embed in the object:
function fnTest(a,b,c) {
return (typeof a == "object" && typeof b == "object" && c) ? c : "";
};
userObj = {name:{
first: fnTest(req, req.body, req.body.first)
,last: fnTest(req,req.body, req.body.last)
},location:{
city: fnTest(req,req.body,req.body.city)
},phone: fnTest(req.body.phone)
};

Checking existence of nested property in an object javascript

I have already reviewed some of the answers to similar questions, however, I want to ask my question differently.
Let's say we have a string like "level1.level2.level3. ..." that indicates a nested property in an object called Obj.
The point is that we may not know how many nested properties exist in this string. For instance, it may be "level1.level2" or "level1.level2.level3.level4".
Now, I want to write a function, that given the Obj and the string of properties as input, to simply tell us if such a nested property exists in the object or not (let's say true or false as output).
Update:
Thanks to #Silvinus, I found the solution with a minor modification:
private checkNestedProperty(obj, props) {
var splitted = props.split('.');
var temp = obj;
for (var index in splitted) {
if (temp[splitted[index]] === 'undefined' || !temp[splitted[index]]) return false;
temp = temp[splitted[index]];
}
return true;
}
You could use Array#every() and thisArg of it, by iterating the keys and checking if it is in the given object.
var fn = function (o, props) {
return props.split('.').every(k => k in o && (o = o[k], true));
}
console.log(fn({}, "toto.tata")); // false
console.log(fn({ toto: { tata: 17 } }, "toto.tata")); // true
console.log(fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata")); // false
console.log(fn({ toto: { tata: false } }, "toto.tata")); // true
You can explore your Obj with this function :
var fn = function(obj, props) {
var splited = props.split('.');
var temp = obj;
for(var index in splited) {
if(typeof temp[splited[index]] === 'undefined') return false;
temp = temp[splited[index]]
}
return true
}
var result = fn({ }, "toto.tata");
console.log(result); // false
var result = fn({ toto: { tata: 17 } }, "toto.tata");
console.log(result); // true
var result = fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata");
console.log(result); // false
This function allow to explore nested property of Obj that depends of props passed in parameter
This answer provides the basic answer to your question. But it needs to be tweaked to handle the undefined case:
function isDefined(obj, path) {
function index(obj, i) {
return obj && typeof obj === 'object' ? obj[i] : undefined;
}
return path.split(".").reduce(index, obj) !== undefined;
}
Based on the solution given by #Silvinus here is a solution if you deal with array inside nested objects (as it is often the case in results from databases queries) :
checkNested = function(obj, props) {
var splited = props.split('.');
var temp = obj;
for(var index in splited) {
var regExp = /\[([^)]+)\]/;
var matches = regExp.exec(splited[index])
if(matches) {
splited[index] = splited[index].replace(matches[0], '');
}
if(matches) {
if(matches && typeof temp[splited[index]][matches[1]] === 'undefined') return false;
temp = temp[splited[index]][matches[1]];
}
else {
if(!matches && typeof temp[splited[index]] === 'undefined') return false;
temp = temp[splited[index]]
}
}
return true
}
obj = {ok: {ao: [{},{ok: { aa: ''}}]}}
console.log(checkNested(obj, 'ok.ao[1].ok.aa')) // ==> true
console.log(checkNested(obj, 'ok.ao[0].ok.aa')) // ==> false

Javascript array with associative array difference

Is there a way to return the difference between two arrays in JavaScript?
I can not use indexOf in this case.
For example:
var a1 = [{"a":"A"},{"b":"B"}];
var a2 = [{"a":"A"},{"b":"B"},{"c":"C"}];
// need [{"c":"C"}]
Please advise.
One object can never be the same as another object even if they have the same content. They would still be different instances of Objects.
That means you have to compare keys and values to check that they match, or in this case, don't match.
var a1 = [{"a":"A"},{"b":"B"}];
var a2 = [{"a":"A"},{"b":"B"},{"c":"C"}];
var a3 = a2.filter(function(o) {
return Object.keys(o).some(function(k) {
return a1.every(function(o2) {
return !(k in o2) || (o2[k] != o[k]);
});
});
});
FIDDLE
As I mentioned in my comment, objects are only equal if they refer to the same instance. Therefore, any built-in system will not do, least of all == and ===. So, first you must define your own comparison function.
Let's say that two objects are equal if they contain the same keys with the same values.
function areObjectsEqual(a,b) {
function helper(a,b) {
var k;
for( k in a) {
if( a.hasOwnProperty(k)) {
if( !b.hasOwnProperty(k)) return false;
if( typeof a[k] != typeof b[k]) return false;
if( typeof a[k] == "object") {
if( !areObjectsEqual(a[k],b[k])) return false;
// the above line allows handling of nested objects
}
else {
if( a[k] != b[k]) return false;
// this comparison is technically strict
// because we already checked typeof earlier
}
}
}
}
return helper(a,b) && helper(b,a);
}
Okay, now that that's out of the way, we can compare our functions.
function array_diff(a,b) {
var result = [], l = a.length, i, m = b.length, j;
outer:
for( i=0; i<l; i++) {
for( j=0; j<m; j++) {
if( typeof a[i] != typeof b[j]) continue;
if( typeof a[i] == "object") {
if( !areObjectsEqual(a[i],b[j])) continue;
}
else {
if( a[i] != b[j]) continue;
}
// if we got to here, it's a match!
// ... so actually we want to skip over the result :p
continue outer;
}
// okay, if we get HERE then there was no match,
// because we skipped the "continue outer"
result.push(a[i]);
}
return result;
}
And there you go!
Easy and simple way to achieve your goal
var a1 = [{"a":"A"},{"b":"B"}];
var a2 = [{"a":"A"},{"c":"C"},{"b":"B"}];
var max = (a1.length > a2.length) ? a1 : a2;
var min = (a1.length > a2.length) ? a2 : a1;
var newArray = [];
for ( var i = 0; i < max.length; i++ ) { // saving elements into string
max[i] = JSON.stringify(max[i]);
if ( typeof min[i] !== undefined ) {
min[i] = JSON.stringify(min[i]);
}
}
for ( var i = 0; i < max.length; i++ ) { // checking values uniqueness
if ( min.indexOf(max[i]) === -1 ) {
newArray.push(max[i]);
}
}
// if you need new Array's elements back in object do following iteration
for ( var i in newArray ) { // loop recreate results array's elements into object again
newArray[i] = JSON.parse(newArray[i]);
}
console.log(newArray); // result : [Object { c="C"}]
JSFiddle
var a1 = [{"a":"A"},{"b":"B"}];
var a2 = [{"a":"A"},{"b":"B"},{"c":"C"}];
var obj = {}, result = [];
function updateObjectCount(currentItem) {
var keys, key;
for (key in currentItem) {
if (currentItem.hasOwnProperty(key)) {
keys = key;
break;
}
}
obj[key] = obj[key] || {};
obj[key][currentItem[key]] = (obj[key][currentItem[key]] || 0) + 1;
}
a1.forEach(updateObjectCount);
a2.forEach(updateObjectCount);
for (var key1 in obj) {
if (obj.hasOwnProperty((key1))) {
for (var key2 in obj[key1]) {
if (obj.hasOwnProperty((key1))) {
if (obj[key1][key2] === 1) {
var temp = {};
temp[key1] = key2;
result.push(temp)
}
}
}
}
}
console.log(result);
# [ { c: 'C' } ]

return key value pair from object whose key matches certain condition with javascript and underscore

var obj = {
"M_18-24":413109,
"F_18-24":366159,
"F_25-34":265007,
"U_25-34":1214,
"U_35-44":732
}
I want to return an object with key value pairs whose keys start with either "M" or "F". So the final object would look like
var obj = {
"M_18-24":413109,
"F_18-24":366159,
"F_25-34":265007
}
I've tried things like _.filter(obj, function(v,k) { return /^[MF]/.test(k) })...
this will do the trick:
function filte_obj_FM (inp)
{
var ret = {};
for ( var k in inp)
{
if ( k[0] == "M" || k[0] == "F" )
{
ret[k] = inp[k];
}
}
return ret;
}
see console output (F12 +-> see console) here: http://jsfiddle.net/vH3ym/2/
You can try
for (var prop in obj) { console.log(prop) }
It will give you the corresponding properties, then you can add your logic like
if(prop.indexOf('M'))
This should work:
var obj = {
"M_18-24":413109,
"F_18-24":366159,
"F_25-34":265007,
"U_25-34":1214,
"U_35-44":732
}
var filtered = {}
for(var key in obj) {
if(key[0] === "M" || key[0] === "F"){
filtered[key] = obj[key]
}
}
Another version this time using reduce:
// create a new underscore function that will return the properties from an object that pass a given predicate
_.mixin({ filterProperties: function(obj, predicate){
return _.reduce(obj, function(memo, value, key){
if( predicate(key) ){
memo[key] = value;
}
return memo;
}, {});
}});
// A couple of predicates that we can use when calling the new function
function isMale(key){
return key[0] == 'M';
}
function isFemale(key){
return key[0] == 'F';
}
// and finally getting the data we want:
var males = _.filterProperties( obj, isMale );
var females = _.filterProperties( obj, isFemale );
Here's my solution:
_.filter(_.keys(obj), function(key) {
return key.match(/U/);
}).forEach(function(kv) {
delete obj[kv];
});
I think all of yours are good and I voted them up. Thanks!

Convert Javascript Object (incl. functions) to String

Hey, Im trying to convert specific javascript objects to a String. So far I'm working with json2.js. As soon as my Object contain functions, those functions are stripped. I need a way to convert functions too, any ideas?
There is a toString() method for functions in firefox, but how to make that work with json2.js?
Actually, I think it is possible and easy. At least when doing jsonP with nodeJS it works for me just fine, and it's demonstratable by the following fiddle.
I did it by simply adding strings to a function:
var anyString = '';
var aFunction = function() { return true; };
var functionToText = anyString + aFunction;
console.log(functionToText);
here's the fiddle: http://jsfiddle.net/itsatony/VUZck/
Use String() function http://www.w3schools.com/jsref/jsref_string.asp
var f = function(a, b){
return a + b;
}
var str = String(f);
convert obj to str with below function:
function convert(obj) {
let ret = "{";
for (let k in obj) {
let v = obj[k];
if (typeof v === "function") {
v = v.toString();
} else if (v instanceof Array) {
v = JSON.stringify(v);
} else if (typeof v === "object") {
v = convert(v);
} else {
v = `"${v}"`;
}
ret += `\n ${k}: ${v},`;
}
ret += "\n}";
return ret;
}
input
const input = {
data: {
a: "#a",
b: ["a", 2]
},
rules: {
fn1: function() {
console.log(1);
}
}
}
const output = convert(input)
output
`{
data: {
a: "#a",
b: ["a", 2]
},
rules: {
fn1: function() {
console.log(1);
}
}
}`
// typeof is String
convert back
const blob = new Blob([output], { type: 'application/javascript' })
const url = URL.createObjectURL(blob)
import(url).then(input => {
/** parse input here **/
})
The short answer is that you cannot convert arbitrary JavaScript functions to strings. Period.
Some runtimes are kind enough to give you the string serialization of functions you defined but this is not required by the ECMAScript language specification. The "toString()" example you mentioned is a good example of why it cannot be done - that code is built in to the interpreter and in fact may not be implemented in JavaScript (but instead the language in which the runtime is implemented)! There are many other functions that may have the same constraints (e.g. constructors, built-ins, etc).
I made a improved version based on the #SIMDD function, to convert all types of objects to string.
Typescript code:
function anyToString(valueToConvert: unknown): string {
if (valueToConvert === undefined || valueToConvert === null) {
return valueToConvert === undefined ? "undefined" : "null";
}
if (typeof valueToConvert === "string") {
return `'${valueToConvert}'`;
}
if (
typeof valueToConvert === "number" ||
typeof valueToConvert === "boolean" ||
typeof valueToConvert === "function"
) {
return valueToConvert.toString();
}
if (valueToConvert instanceof Array) {
const stringfiedArray = valueToConvert
.map(property => anyToString(property))
.join(",");
return `[${stringfiedArray}]`;
}
if (typeof valueToConvert === "object") {
const stringfiedObject = Object.entries(valueToConvert)
.map((entry: [string, unknown]) => {
return `${entry[0]}: ${anyToString(entry[1])}`;
})
.join(",");
return `{${stringfiedObject}}`;
}
return JSON.stringify(valueToConvert);
}
Vanilla Javascript code:
function anyToString(valueToConvert) {
if (valueToConvert === undefined || valueToConvert === null) {
return valueToConvert === undefined ? "undefined" : "null";
}
if (typeof valueToConvert === "string") {
return `'${valueToConvert}'`;
}
if (typeof valueToConvert === "number" ||
typeof valueToConvert === "boolean" ||
typeof valueToConvert === "function") {
return valueToConvert.toString();
}
if (valueToConvert instanceof Array) {
const stringfiedArray = valueToConvert
.map(property => anyToString(property))
.join(",");
return `[${stringfiedArray}]`;
}
if (typeof valueToConvert === "object") {
const stringfiedObject = Object.entries(valueToConvert)
.map((entry) => {
return `${entry[0]}: ${anyToString(entry[1])}`;
})
.join(",");
return `{${stringfiedObject}}`;
}
return JSON.stringify(valueToConvert);
}
ATENTION!
I am using the function Object.entries(), winch currently is a draft. So if you are not using Babel or typescript to transpile your code, you can replace it with a for loop or the Object.keys() method.
Combining a few options
var aObj = {
v: 23,
a: function() {
return true;
}
};
var objStr = '';
for (var member in aObj) {
objStr += (objStr ? ',\n': '')+
member + ':' + aObj[member] + '';
}
console.log('{\n'+
objStr + '\n}');
JSFiddle
functionName.toString() will return a string of all the function code.
I cut is after the name.
var funcString = CurrentButton.clickFunc.toString();
console.log("calling:" + funcString.substr(0, funcString.indexOf(")")-1));
// utility for logging
var log = function(s){
var d = document.getElementById('log');
var l = document.createElement('div');
l.innerHTML = (typeof s === 'object')?JSON.stringify(s):s;
d.appendChild(l);
}
// wrapper function
var obj = {
'x-keys': {
'z': function(e){console.log(e);},
'a': [function(e){console.log('array',e);},1,2]
},
's': 'hey there',
'n': 100
};
log(obj);
// convert the object to a string
function otos(obj){
var rs = '';
var not_first = false;
for(var k in obj){
if(not_first) rs += ',';
if(typeof obj[k] === 'object'){
rs += '"'+k+'": {'+otos(obj[k])+'}';
}
else if(typeof obj[k] === 'string' || typeof obj[k] === 'function'){
rs += '"'+k+'":"'+obj[k]+'"';
}
else if(typeof obj[k] === 'number'){
rs += '"'+k+'":'+obj[k]+'';
}
else {
// if it gets here then we need to add another else if to handle it
console.log(typeof obj[k]);
}
not_first = true;
}
return rs;
}
// convert a string to object
function stoo(str){
// we doing this recursively so after the first one it will be an object
try{
var p_str = JSON.parse('{'+str+'}');
}catch(e){ var p_str = str;}
var obj = {};
for(var i in p_str){
if(typeof p_str[i] === 'string'){
if(p_str[i].substring(0,8) === 'function'){
eval('obj[i] = ' + p_str[i] );
}
else {
obj[i] = p_str[i];
}
}
else if(typeof p_str[i] === 'object'){
obj[i] = stoo(p_str[i]);
}
}
return obj;
}
// convert object to string
var s = otos(obj);
log(s);
// convert string to object
var original_obj = stoo(s);
log(original_obj);
log( original_obj['x-keys'].z('hey') );
log( original_obj['x-keys'].a[0]('hey') );
<div id='log'></div>
I realize this is very old but I have a solution here
https://jsfiddle.net/stevenkaspar/qoghsxhd/2/
May not work for all cases but it is a good start
It will convert this into a string and then back into an object and you can run the functions
var obj = {
'x-keys': {
'z': function(e){console.log(e);},
'a': [function(e){console.log('array',e);},1,2]
},
's': 'hey there',
'n': 100
};
Just provide the object to this function. (Look for nested function) Here:
function reviveJS(obj) {
return JSON.parse(JSON.stringify(obj, function (k, v) {
if (typeof v === 'function') {
return '__fn__' + v;
}
return v;
}), function (k, v) {
if (typeof v === 'string' && v.indexOf('__fn__') !== -1) {
return v;
}
return v;
});
}
UPDATE
A slightly decent code than above which I was able to solve is here http://jsfiddle.net/shobhit_sharma/edxwf0at/
I took one of answers above, it worked fine, but didn't inlcude case then array includes function. So i modified it and it works fine for me.. Sharing the code.
function convert(obj,ret="{") {
function check(v) {
if(typeof v === "function") v = v.toString()
else if (typeof v === "object") v = convert(v)
else if (typeof v == "boolean" || Number.isInteger(v)) v=v
else v = `"${v}"`
return v
}
if(obj instanceof Array) {
ret="["
obj.forEach(v => {
ret += check(v)+','
});
ret += "\n]"
} else {
for (let k in obj) {
let v = obj[k];
ret += `\n ${k}: ${check(v)},`;
}
ret += "\n}";
}
return ret
}
So I was just testing your script on one of my project, and there's a problem with Object keys that contain special characters (like / or -).
You should consider wrapping theses keys with quotes.
return `"${entry[0]}" : ${anyToString(entry[1])}`;

Categories

Resources