Is it possible to change the`key`of an object?

Asked

Viewed 63 times

2

I have 1 array and 1 object:

headers: [
  {
    id: 1,
    title: 'tab-1'
  },
  {
    id: 2,
    title: 'tab-2'
  },
  {
    id: 3,
    title: 'tab-3'
  }
]

contents: {
  1: {
    id: 1,
    fields: []
  },
  2: {
    id: 2,
    fields: []
  },
  3: {
    id: 3,
    fields: []
  }
}

When I delete one header, for example that of id 2, I have to delete the content whose key/id be equal to 2 too. Until then quiet, I used the index and made a delete and ready.

But when I do that I need them contents that are left stay in order:

  • the 1 stays as is
  • like the 2 was deleted, the 3 must have his key changed to 2 and the id too

It is possible to change this key? Or will I have to delete and create a new object for it? Would I have any alternative to it?

  • 1

    Well, one way to do it:;delete contents[KeyToDelete]; contents.filter(el => el != null);

  • 1

    Maybe there is some method using Underscore or Lodash, but I believe that in the core they do something similar, https://i.stack.Imgur.com/Xldji.png Now to change the id lets you see here

  • 1

    I believe that answers contents.map((el, key) => ({ ...el, id: key })).filter(el => el != null);

  • "Contents.map is not a Function", brother.. cannot use map in an object..!

  • 1

    Just use Object.Entries(Contents), but it is necessary some adjustments, I already update :)

  • 2

    @wDrik, could you [Edit] your question to put the code you’ve tried to do? :)

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.