【问题标题】:JavaScript: grab each nested object / flatten the top level of the object onlyJavaScript:抓取每个嵌套对象/仅展平对象的顶层
【发布时间】: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


【解决方案1】:

如果您有一个对象数组,您可以通过将所有对象分散到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; }

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 2020-06-23
    • 1970-01-01
    • 2019-07-20
    • 2018-10-24
    • 2020-03-02
    • 2017-07-02
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多