1

Here is an object:

var a = { a: 1, b: 2, c: 3};

I would need to square all values from this object and the keys to remain the same, so new object to look like this:

var a1 = {a: 1, b: 4, c: 9}

My code - I extracted the keys and the values and created two separate arrays:

var a = {a:1, b: 2, c:3};
let key = Object.keys(a);
let value = Object.values(a);
v = [];
for (var i=0; i<value.length;i++){
  value[i]**2;
  v.push(value[i]**2);
}
console.log(v);

So here I got the array with squared values of all elements, but I don't know how to return it back to the object and get

{a: 1, b: 4, c: 9}
VLAZ
  • 22,934
  • 9
  • 44
  • 60
Ivan Vrzogic
  • 135
  • 1
  • 8

3 Answers3

3

To keep key and value together, you could work with the entries of the object and map new pairs and build an object from the new entries.

Methods:

const
    object = { a: 1, b: 2, c: 3 },
    result = Object.fromEntries(Object
        .entries(object)
        .map(([key, value]) => [key, value * value])
    );

console.log(result);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

You can also use Array.reduce on Object.entries. I.e.

const a = {
  a: 1,
  b: 2,
  c: 3
};

const result = Object.entries(a).reduce((acc, [key, value]) => {
  acc[key] = value ** 2;
  return acc
}, {})
adiga
  • 31,610
  • 8
  • 53
  • 74
Zoltan Magyar
  • 864
  • 1
  • 6
  • 18
  • [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Feb 16 '21 at 14:24
0

var a = {
  a: 1,
  b: 2,
  c: 3
};

Object.keys(a).map(function(key, index) {
  a[key] = a[key] * a[key];
});

console.log(a)
Tushar Wason
  • 356
  • 1
  • 7