【发布时间】:2020-06-22 07:41:45
【问题描述】:
所以我目前有一个对象数组的一部分,看起来像这样:
props: {
dog: {
default: '',
type: String
},
cat: {
default: '',
type: String
},
bird: {
default: '',
type: String
}
},
{
dog: {
default: '',
type: String
},
bird: {
default: '',
type: String
},
fish: {
default: '',
type: String
}
}
我想要的是基本上展平对象数组的顶层,以便它在同一级别上拥有所有嵌套对象(并且显然没有重复),如下所示:
{
dog: {
default: '',
type: String
},
bird: {
default: '',
type: String
},
fish: {
default: '',
type: String
}
}
如果我知道结构中始终包含哪些键,这会容易得多,但我不知道,所以我需要能够在不指定任何键名的情况下循环遍历它。我试图至少抓住每个单独的嵌套对象并将每个对象推入一个数组,如下所示:
const newArray = [];
for (let i = 0; i < objSize; i++) {
// checks if properties exist
if (JSON.stringify(petObj[i].options.props) !== '{}') {
newArray.push(petObj[i].options.props);
const numProps = Object.keys(newArray[i]).length;
for (let j = 0; j < numProps.length; j++) {
console.log(petObj[i].options.props[j]);
}
}
但这似乎不起作用,因为在添加内部 for 循环后出现 null/undefined 错误。有人愿意提供可能的解决方案吗?
【问题讨论】:
-
props是一个数组吗?否则您的数据无效。 -
是的,抱歉,我是这么说的。
标签: javascript arrays object flatten