I have an object as input, how can I return a modified object at the output based on an existing one?

I used Object.keys() for this in conjunction with the map() iterator ... But something doesn't work, I get unefined at the output

  let objjjj = { a: 2, b: 3, c: 4 } console.log( Object.keys(objjjj).map((key, i) => { key: objjjj[key] + 1 } ) ) 

  • one
    What should the result be as a result? - Grundy

1 answer 1

  • Create an empty final object
  • Take the keys of the original object (by condition, using Object.keys )
  • For each key, add the key to the final object with a value equal to the value from the original object plus one

Summary Code:

 let objjjj = { a: 2, b: 3, c: 4 }; let result = {}; Object.keys(objjjj).forEach(key => { result[key] = objjjj[key] + 1; }); console.log(result); 


What is wrong with the map in the source code:

  • In { key: objjjj[key] + 1 } braces are perceived not as the creation of a new object, but as the boundaries of the body of an arrow function. The object must be returned as { return { key: objjjj[key] + 1 }; } { return { key: objjjj[key] + 1 }; }
  • However, then the key name will be interpreted as "key", and not as the key value. Therefore, you need to make [key]:
  • The result is an array of objects, each of which has one key value from the source object. You need to combine them into a single object (for example, using the reduce and Object.assign )

Summary Code:

 let objjjj = { a: 2, b: 3, c: 4 }; let result = Object.keys(objjjj).map(key => { return { [key]: objjjj[key] + 1 }; }).reduce((acc, cur) => Object.assign(acc, cur), {}); console.log(result);