JavaScript:抓取每个嵌套对象/仅展平对象的顶层
JavaScript: grab each nested object / flatten the top level of the object only
所以我目前有一个对象数组的一部分,如下所示:
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 错误。有人愿意提供可能的解决方案吗?
如果你有一个对象数组,你可以通过将它们分散到 Object.assign
来合并所有对象。
var data = { 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 } }] },
result = Object.assign({}, ...data.props);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
所以我目前有一个对象数组的一部分,如下所示:
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 错误。有人愿意提供可能的解决方案吗?
如果你有一个对象数组,你可以通过将它们分散到 Object.assign
来合并所有对象。
var data = { 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 } }] },
result = Object.assign({}, ...data.props);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }