Michael
Michael

Reputation: 1353

How can I filter an object of all properties that are objects?

I'm trying to make a copy of an object that only includes the properties that are not objects. But the child objects get copied along with it.

var testObject = {
  stringProperty: "hi",
  intProperty: 4,
  objectProperty: {},
  nullProperty: null
};

console.log(removeChildObjects(testObject));

function removeChildObjects(object) {
  var keys = Object.keys(object);
  var newObject = {};
  keys.forEach(function(key) {
    console.log(key, object[key], typeof object[key]);
    if (typeof object[key] != "object") {
      newObject[key] = object[key];
    }
  });
  return object;
}

Also check it out here https://jsfiddle.net/uss94sc3/1/

Upvotes: 0

Views: 55

Answers (4)

Redu
Redu

Reputation: 26191

You may try this

var testObject = {
                  stringProperty: "hi",
                     intProperty: 4,
                  objectProperty: {},
                    nullProperty: null
                 };
var filterPrimitive = o => Object.keys(o).reduce((p,k) => {typeof o[k] != "object" && (p[k] = o[k]); return p},{});

document.write("<pre>" + JSON.stringify(filterPrimitive(testObject),null,2) + "</pre>");

Upvotes: 0

Francesco Pezzella
Francesco Pezzella

Reputation: 1795

If you want to strictly filter out object properties (keeping null and undefined properties), then you cannot rely on the broken typeof unary operator.

typeof null
// "object"

You can either change your code to:

function removeChildObjects(object) {
    var keys = Object.keys(object);
    var newObject = {};
    keys.forEach(function(key) {
        if (typeof object[key] != "object" || object[key] == null) {
            newObject[key] = object[key];
        }
    });
    return newObject;
}

or more succinctly with underscore:

function removeChildObjects(object) {
    return _.omit(object, _.isObject);
}

Upvotes: 1

isvforall
isvforall

Reputation: 8926

You return the same object that passed:

return object;

You should return newObject

return newObject;

Upvotes: 0

blex
blex

Reputation: 25659

Try replacing return object; with return newObject;. It will work a lot better!

https://jsfiddle.net/w3urvpjq/

Upvotes: 0

Related Questions