JavaScript:抓取每个嵌套对象/仅展平对象的顶层

问题描述 投票:0回答:1

因此,我目前有一部分对象看起来像这样:

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错误。有人在乎提供可能的解决方案吗?

javascript arrays object flatten
1个回答
1
投票

如果有对象数组,则可以通过将所有对象散布到Object.assign来合并所有对象。

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);
© www.soinside.com 2019 - 2024. All rights reserved.