[英]Given a nested object I need to read values and display output in array
输入 -
{
name: 'hi',
rollNo: {
id: 3,
sub: {
type: ['math','science']
}
}
}
输出["hi",3,"math","science"]
我写的代码
var flattenObject = function(obj){
for(var i in obj){
if(!obj.hasOwnProperty(i))continue;
if(typeof obj[i] === "object" && !Array.isArray(obj[i]) && obj[i] !== null){
flattenObject(obj[i]);
}
if(Array.isArray(obj[i]) && obj[i] !== null){
//handling array condition
}
result.push(obj[i]);
}
console.log("Array",result);
return result;
}
对此有任何线索,或者可能有其他方法可以解决?
您可以使用递归flatMap
。
const o = { name: 'hi', rollNo: { id: 3, sub: { type: ['math', 'science'] } } }; const getEntries = (o, f) => { const obj = f? o[1]: o; return obj === Object(obj)? Object.entries(obj).flatMap(e => getEntries(e, true)): [o]; } console.log(getEntries(o));
You can try with Object.values
, witch return values for all enumerable props, if specific value is object (works also for arrays but not nulls) you can recursively call the function. 如果你想跳过 nulls/undefined 添加一些if
和continue
。
function values(obj) {
var v = Object.values(obj);
var out = [];
for (let i = 0; i < v.length; i++) {
const element = v[i];
if (element !== null && typeof element === 'object') {
out = out.concat(values(element));
continue;
}
out.push(element);
}
return out;
}
输入:
var xx = {
name: 'hi',
rollNo: {
id: 3,
sub: {
type: ['math', 'science']
},
undef: undefined,
nil: null,
fal: false,
ze: 0
}
};
output:
[ 'hi', 3, 'math', 'science', undefined, null, false, 0 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.