JavaScript 将对象展平为单一深度的对象
给定一个嵌套的JavaScript对象,任务是将对象展平并提取出所有的值到单一深度。如果值已经在单一深度上,则返回结果不变。
typeof()方法: typeof()方法用于在脚本中检查JavaScript变量的类型。
语法:
typeof(variable)
参数: 该方法接受一个如上所述的参数,并如下所述进行描述:
- variable: 输入变量。
返回值: 该方法返回一个包含传递变量类型的字符串。
方法:
- 我们创建一个叫做flatten object的函数,该函数接受一个对象作为输入,并返回一个对象。
- 循环遍历对象,并检查当前属性的类型:
- 如果它是对象类型,并且不是数组,则递归调用该函数。
- 否则,将值存储在结果中。
- 返回该对象。
示例:
// Declare an object
let ob = {
Company: "GeeksforGeeks",
Address: "Noida",
contact: +91-999999999,
mentor: {
HTML: "GFG",
CSS: "GFG",
JavaScript: "GFG"
}
};
// Declare a flatten function that takes
// object as parameter and returns the
// flatten object
const flattenObj = (ob) => {
// The object which contains the
// final result
let result = {};
// loop through the object "ob"
for (const i in ob) {
// We check the type of the i using
// typeof() function and recursively
// call the function again
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// Store temp in result
result[i + '.' + j] = temp[j];
}
}
// Else store ob[i] in result directly
else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(ob));
输出:
{
Company: 'GeeksforGeeks',
Address: 'Noida',
contact: -999999908,
'mentor.HTML': 'GFG',
'mentor.CSS': 'GFG',
'mentor.JavaScript': 'GFG'
}
极客教程