简体   繁体   English

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

[英]JavaScript: grab each nested object / flatten the top level of the object only

So I currently have part of an array of objects that looks like this:所以我目前有一个对象数组的一部分,如下所示:

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
       }
     }

What I want is to essentially flatten the top level of the array of objects so that it has all the nested objects on the same level (and obviously without duplicates), like so:我想要的是基本上展平对象数组的顶层,以便它具有同一级别的所有嵌套对象(显然没有重复),如下所示:

{
   dog: {
     default: '',
     type: String
   },
   bird: {
     default: '',
     type: String
   },
   fish: {
     default: '',
     type: String
   }
}

This would be much easier if I knew what keys were always going to be in the structure, however I don't, so I need to be able to loop through it without specifying any key names.如果我知道结构中总是会有哪些键,这会容易得多,但我不知道,所以我需要能够在不指定任何键名的情况下遍历它。 I've tried to at least grab each individual nested object and push each into an array like this:我试图至少抓住每个单独的嵌套对象并将每个对象推入这样的数组:

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]);
    }
  }

but that doesn't seem to be working since I get null/undefined errors after adding the inner for loop.但这似乎不起作用,因为在添加内部 for 循环后出现空/未定义错误。 Anyone care to offer a possible solution?有人愿意提供可能的解决方案吗?

If you got an array of objects, you could merge all objects by spreading them to 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);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM