让我们为版主添加前缀,这个问题与嵌套的 Key 无关。这是关于对象中的数组,以及如何查看它是仅包含值的简单数组还是包含对象的数组以及如何获取这些对象的键。我包含了解析样本并检测 2 个数组的代码片段。如果数组是只有一个值列表的简单数组,我正在寻找的是只返回数组的名称。如果数组是对象数组,我想在数组中获取该对象的键。
obj = {
DocId: "email_campaign::3ed76589-4063-49f6-a21e-9ca16981d102",
history: {
created_by: "",
created_on: "",
update_on: "",
updated_by: ""
},
librarys :[{id: 1, name : 'Lib 1'},{ id: 2, name: 'Lib 2'}],
status: "Active",
subject: "Test 1 Subject",
summary: "",
tags: ['one', 'two'],
template_id: ""
};
const keyify = (obj, prefix = '') =>
Object.keys(obj).reduce((res, el) => {
if( Array.isArray(obj[el]) ) {
// Here needs to go the Array Part
console.log(el + ' is Array')
return [...res, el];
} else if( typeof obj[el] === 'object' && obj[el] !== null ) {
return [...res, ...keyify(obj[el], prefix + el + '.')];
} else {
return [...res, el];
}
}, []);
const output = keyify(obj);
console.log(output);
假设您希望数组名称的前缀类似于对象的现有前缀,您可以尝试以下操作:
const keyify = (obj, prefix = "") =>
Object.keys(obj).reduce((res, el) => {
const elDisplayName = `${prefix}${el}`;
if (Array.isArray(obj[el])) {
const objectsInArray = obj[el].filter(el => typeof el === "object");
if (objectsInArray.length > 0) {
let objectKeys = [];
objectsInArray.map(object => {
objectKeys = objectKeys.concat(keyify(object, prefix + el + "."))
});
return [...res, ...new Set(objectKeys)];
}
return [...res, elDisplayName];
} else if (typeof obj[el] === "object" && obj[el] !== null) {
return [...res, ...keyify(obj[el], prefix + el + ".")];
} else {
return [...res, elDisplayName];
}
}, []);
这个解决方案有很多注意事项,比如假设一个数组只有一个对象,它将只包含对象。但这应该让您开始检测数组中对象的存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句