[英]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/ 也可以在这里查看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. 如果要严格滤除对象属性(保留
null
和undefined
属性),则不能依赖残破的typeof
一元运算符。
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;
尝试更换
return object;
with return newObject;
return newObject;
. 。 It will work a lot better!
它将更好地工作!
https://jsfiddle.net/w3urvpjq/ https://jsfiddle.net/w3urvpjq/
You return the same object that passed: 您返回传递的同一对象:
return object;
You should return newObject
您应该返回
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>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.