1

I need to find a key that contains an object in a. It should not return me a key that contains array or string . For example in a it should return me d but not b or c

a = {"b" : "hi","c":[1,2,3],"d":{"2:":3}};

Here is the snipped I tried. It returns me first instance of Object. But I dont need Array instance just a dict.

var _ = require(underscore);    
_.findKey(a,_.isObject);
1
  • 1
    _.isObject won't work for this, because arrays are objects. Commented Sep 16, 2016 at 20:41

2 Answers 2

2

You can use regular JS for this:

var keysThatContainObjects = Object.keys(a).filter(function(k) {
    return typeof a[k] === "object" && !Array.isArray(a[k]);
}); //["d"]

1 line

var keysThatContainObjects = Object.keys(a).filter(function(k) { return typeof a[k] === "object" && !Array.isArray(a[k]); }); //["d"]
Sign up to request clarification or add additional context in comments.

7 Comments

what if the object has a length property? Maybe it would be better to use !Array.isArray(a[k])...
@RobM. -- Good point, made the edit - definitely didnt think of that.
any way to do in one line,,,thats wat my interest !!!!! and thats the reason to try it in underscore
@VivekSrinivasan -- Remove the line breaks - now it's one line.
Or use ES6 fat arrow function k => typeof a[k] === "object" && !Array.isArray(a[k])
|
0

I very clean way would be to use pick from underscore

var a = {"b" : "hi","c":[1,2,3],"d":{"2:":3}};
var aFiltered = _.pick(a, function() {
  return _.isObject(value);
});

1 Comment

it picks even an array type ...I need only dict . in the return statement we need negate array type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.