Don't understand objects

Hi folks, i want to iterate over array of objects and rename two keys, i want to keep others as they are.

here is my code:

    const translated = => {
      return { typ: obj.objType, name: obj.caption}

This returns object with only typ and name, all other values are deleted .
why is that ?

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

i don’t use trim() function at all, “trimmed” is the name of the array i am iterating over

that’s what you wrote in the function

or you mention all properties you want to keep

or, you could iterate over the array of objects and proceed in a different way:

  • save the property value in a variable
  • use the delete keyword to remove the property from the object
  • add new property with dot or beacket notation

@Stivis hey,

I dont know if you can rename the key with map, you could try something like this

 trimmed.forEach((obj) => {
    obj.typ = obj.objType
    delete obj.objType = obj.caption
    delete obj.caption     
1 Like

Meanwhile i have read some things and from what i understand,object is mutated, trying to keep rest of the object by using …spread operator. Don’t understand it quite much

yes this is how you would do it if you wanted to change the value but not the key.

 const translated = => {
      return { 
        obj.objType: 'new type', 
        obj.caption: 'new caption'

map returns a new array, and if you write an object literal (graph parenthesis with key value pairs inside) then you are also creating a new array for each element of the array, nothing is mutated

Thanks a lot! this worked like a charm

nothing is mutated because map() returns new array ?
I think i understand much better now. Thank you

map returns a new array, but also you write {...} and that’s a new object

1 Like