Если у вас есть вложенные объекты, вы можете использовать простой рекурсивный алгоритм, чтобы установить любое значение, которое не является объектом, на undefined
, а затем рекурсивно применить то же преобразование к любым вложенным объектам:
var foo = {
name: 'Leo',
address: '1234 Road',
department: {
name: "accounting",
location: "third floor"
},
favouriteFood: ["pancakes", "fish"]
};
var bar = someFunction(foo);
console.log(bar);
function someFunction(input) {
//return `undefined` for primitives and arrays
if (typeof input !== "object" || Array.isArray(input))
return undefined;
//otherwise go over all the entries of the object
return Object.entries(input)
//and make a new object
.reduce((acc, [key, value]) => {
//recursively call `someFunction` to handle the value
var newValue = someFunction(value);
return {
...acc, //copy the object
[key]: newValue //add the current key-(mapped)value pair
};
}, {})
}
Это можно сократить до следующего:
var foo = { name: 'Leo', address: '1234 Road', department: { name: "accounting", location: "third floor" }, favouriteFood: ["pancakes", "fish"]};
var bar = someFunction(foo);
console.log(bar);
function someFunction(input) {
if (typeof input !== "object" || Array.isArray(input))
return undefined;
return Object.entries(input)
.reduce((acc, [key, value]) => ({...acc, [key]: someFunction(value)}), {});
}
А вот реализация, использующая for..of
l oop вместо Array#reduce
:
var foo = { name: 'Leo', address: '1234 Road', department: { name: "accounting", location: "third floor" }, favouriteFood: ["pancakes", "fish"]};
var bar = someFunction(foo);
console.log(bar);
function someFunction(input) {
if (typeof input !== "object" || Array.isArray(input))
return undefined;
const obj = {};
for (const [key, value] of Object.entries(input)) {
obj[key] = someFunction(value);
}
return obj;
}