简体   繁体   中英

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/

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);
}

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

https://jsfiddle.net/w3urvpjq/

You return the same object that passed:

return object;

You should return newObject

return newObject;

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>"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM