0

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

1

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.