1

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. Anyone care to offer a possible solution?

2
  • is props an array? otherwise your data is invalid. Commented Mar 10, 2020 at 11:59
  • Yes it is, sorry, meant to say that. Commented Mar 10, 2020 at 12:01

1 Answer 1

2

If you got an array of objects, you could merge all objects by spreading them to 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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.