Zetsuu
Zetsuu

Reputation: 33

Javascript object conversion and sum values

How can i convert this object of arrays and sum values for each one: in each array i need to sum the values and return a new object.

const obj1 = [
  {
    "array1" : [
        {"value" : 30},
        {"value" : 30}
    ],
    "array2" : [
        {"value" : 30},
        {"value" : 20}
    ],
    "array3" : [
        {"value" : 30},
        {"value" : 40}
    ]
}
]

to an array like this using Javascript :

const obj2 = [
  {
    "key": "array1",
    "value": "60",
  },
  {
    "key": "array2",
    "value": "50",
  },
  {
    "key": "array3",
    "value": "70",
  }
]

Thanks

Upvotes: 0

Views: 33

Answers (1)

Unmitigated
Unmitigated

Reputation: 89234

You can map over the entries of each object, summing the values for each array with Array#reduce.

const obj1 = [
  {
    "array1" : [
        {"value" : 30},
        {"value" : 30}
    ],
    "array2" : [
        {"value" : 30},
        {"value" : 20}
    ],
    "array3" : [
        {"value" : 30},
        {"value" : 40}
    ]
}
];
let res = obj1.flatMap(x => Object.entries(x).map(([key, v]) => 
            ({key, value: "" + v.reduce((a, b) => a + b.value, 0)})));
console.log(res);

Upvotes: 2

Related Questions