HellooooNewman
HellooooNewman

Reputation: 41

Efficient way to map properties from multiple objects to single object with same property names

This is the current way in how i'm doing it now. Wondering if there is a better way as the actual use case is about 150 lines of this. Preferably with a map function or something along those lines.

this.component = {
  item1: 0,
  item2: 2
}

this.otherComponent = {
  item3: 0,
  item4: 2
}
        
this.form = {
  item1: this.component.item1,
  item2: this.component.item2,
  item3: this.otherComponent.item3,
  item4: this.otherComponent.item4,
}

Upvotes: 1

Views: 724

Answers (3)

Yes of course!

You can use the (...)Spread Syntax

this.component = {
  item1: 0,
  item2: 2
}

this.otherComponent = {
  item3: 0,
  item4: 2
}
        
this.form = { ...this.component, ...this.otherComponent }

Example:

let component = {
  item1: 0,
  item2: 2
}

let otherComponent = {
  item3: 0,
  item4: 2
}

let form = {...component, ...otherComponent}
      
console.log(form)

Upvotes: 1

Sweet Chilly Philly
Sweet Chilly Philly

Reputation: 3219

Hey What you can do is spread these objects out:

const a = {
  item1: 0,
  item2: 2
}

const b = {
  item3: 0,
  item4: 2
}
        
const result = {
 ...a,
 ...b
}


This will give desired results

Upvotes: 1

Bergi
Bergi

Reputation: 664630

You're probably looking to use Object.assign:

this.form = Object.assign({}, this.component, this.otherComponent);

or object spread syntax:

this.form = {...this.component, ...this.otherComponent};

Upvotes: 10

Related Questions