Wasteland
Wasteland

Reputation: 5399

js - incorporate an object into an array

I have an array structured as follows:

const screens = [
  {
    name: 'John',
    options: {
      headerTitle: 'Book Title',
    },
  },
  {
    name: 'Bill',
    options: {
      headerTitle: 'Another title',
    },
  },
];

and a piece of data that I need to insert into the 'options:' above. The data I can reshape at will. It could be:

const header = {
    headerStyle: {
      borderBottomWidth: 0.5,
      borderColor: 'black',
    },
};

or

header2 = [
  {
    borderColor: 'red',
    borderWidth: 0.5,
  },
];

The end goal is to have:

const screens = [
      {
        name: 'John',
        options: {
          headerTitle: 'Book Title',
          headerStyle: {
            borderColor: 'red',
            borderWidth: 0.5,
        },
      },
      {
        name: 'Bill',
        options: {
          headerTitle: 'Another title',
          headerStyle: {
            bordercolor: 'red',
            borderWidth: 0.5,
        },
      },
    ];

I have been googling the spread operator but I don't seem to be able to get the two merged.

Upvotes: 0

Views: 34

Answers (2)

Phil
Phil

Reputation: 165069

The idea is to map the existing array to a new one with your options merged

const screens = [{"name":"John","options":{"headerTitle":"Book Title"}},{"name":"Bill","options":{"headerTitle":"Another title"}}]

const header = {
  headerStyle: {
    borderBottomWidth: 0.5,
    borderColor: 'black'
  }
}

const merged = screens.map(screen => ({
  ...screen,
  options: {
    ...screen.options,
    ...JSON.parse(JSON.stringify(header))
  }
}))

console.log(merged)
.as-console-wrapper { max-height: 100% !important; }

One thing to note here is that without the JSON.parse(JSON.stringify(header)), each object in your array will share the same headerStyle object reference. There may be simpler ways to break the object references using spread syntax but given the potential dynamic nature of your object to be merged, using the JSON methods is a convenient catch-all.

Upvotes: 2

nay
nay

Reputation: 1775

if this could help you.
just loop the array and append headerStyle.the three dots means extract data,intend to prevent reference.

const screens = [
  {
    name: 'John',
    options: {
      headerTitle: 'Book Title',
    },
  },
  {
    name: 'Bill',
    options: {
      headerTitle: 'Another title',
    },
  },
];

const header = {
    headerStyle: {
      borderBottomWidth: 0.5,
      borderColor: 'black',
    },
};

screens.forEach(item=>{item.options['headerStyle']={...header.headerStyle}})

console.log(screens)

Upvotes: 1

Related Questions