-1

I am trying to remove "_" from all the keys if data object

data = {
_batch: "Batch", 
_canDelete: true,
_client: "me",
_extension: "MP4",
_type: "video/mp4"
}

Attempted the following:

  for(let k in data ){
      data[k].substring(1) = data[k];
    }
    console.log(data );

Getting the following error: The left-hand side of an assignment expression must be a variable or a property access.

yellowSub
  • 209
  • 3
  • 12
  • 1
    Does this answer your question? [JavaScript Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – Tanner Dolby Aug 19 '21 at 18:45
  • `data[k.substring(1)]`? Otherwise you're calling substring on the _value_, then trying to assign to that (which doesn't make sense). – jonrsharpe Aug 19 '21 at 18:46

3 Answers3

2

You can iterate through the properties (with Object.keys and Array.forEach), copy the value over to the new property and delete the previous property with the delete operator.

const data = {
  _batch: "Batch",
  _canDelete: true,
  _client: "me",
  _extension: "MP4",
  _type: "video/mp4"
}

Object.keys(data).forEach(e => {data[e.substring(1)] = data[e]; delete data[e]})
console.log(data)

If you don't want to mutate the original, you can use Array.reduce:

const data = {
  _batch: "Batch",
  _canDelete: true,
  _client: "me",
  _extension: "MP4",
  _type: "video/mp4"
}

const newData = Object.keys(data).reduce((a, b) => (a[b.substring(1)] = data[b], a), {})
console.log(newData)
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Try this using Object.fromEntries() and Object.entries(). Probably the worst solution in terms of efficiency yet I think it's pretty nice to read.

const data = {
  _batch: "Batch",
  _canDelete: true,
  _client: "me",
  _extension: "MP4",
  _type: "video/mp4",
};

const result = Object.fromEntries(
  Object.entries(data).map((e) => [
    [e[0].substring(1)], e[1]
  ])
);
console.log(result);
Behemoth
  • 5,389
  • 4
  • 16
  • 40
0

Ok, first thing you are doing wrong is that you are trying to assign value of data[k] to the results of substring method call on the data[k], which is well, completely a wrong way of doing things.

If creating a new empty object is not a problem, you could do something like this:

const data = {
  _batch: "Batch", 
  _canDelete: true,
  _client: "me",
  _extension: "MP4",
  _type: "video/mp4"
}

const emptyObj = {};

for(let k in data){ 
  emptyObj[k.substring(1)] = data[k];
}

console.log(emptyObj);

It's by all means not the best solution, but it works!

There's a way cleaner way of doing it with some cool ES6 stuff, but I tried to make it as similar to your example as possible.

avery
  • 16
  • 2