问题
I'm trying to obtain an average value for scores arrays and leave other values from the first object. I can't manage how to loop through the objects to achieve expected output.
const bigArr = [
{
bigDummyData: "string0",
examples: [
{ smallDD: "string00", scores: [1, 1, 5] },
{ smallDD: "string01", scores: [2, 2, 4] },
{ smallDD: "string02", scores: [2, 2, 6] },
],
},
{
bigDummyData: "string1",
examples: [
{ smallDD: "string10", scores: [3, 3, 3] },
{ smallDD: "string11", scores: [2, 2, 2] },
{ smallDD: "string12", scores: [4, 4, 4] },
],
},
]
Expected output its:
output = {
bigDummyData: "string0",
examples: [
{ smallDD: "string00", scores: [2, 2, 4] },
{ smallDD: "string01", scores: [2, 2, 3] },
{ smallDD: "string02", scores: [3, 3, 5] },
],
}
As you can see, bigDummyData and each smallDD are left from the first object.
That's is a simplified example of the problem, arrays bigArr and examples are uploaded dynamically, so they are usually much longer.
回答1:
May be this will help you
const bigArr = [
{
bigDummyData: "string0",
examples: [
{ smallDD: "string00", scores: [1, 1, 5] },
{ smallDD: "string01", scores: [2, 2, 4] },
{ smallDD: "string02", scores: [2, 2, 6] },
],
},
{
bigDummyData: "string1",
examples: [
{ smallDD: "string10", scores: [3, 3, 3] },
{ smallDD: "string11", scores: [2, 2, 2] },
{ smallDD: "string12", scores: [4, 4, 4] },
],
}
]
let firstElement = bigArr[0];
let length = bigArr.length;
bigArr.splice(0,1)
bigArr.forEach(({examples}) => {
examples.forEach(({scores},i) => {
firstElement.examples[i].scores = firstElement.examples[i].scores.map( (x,j) => x+scores[j]);
})
});
firstElement.examples.forEach(({scores},i) => {
firstElement.examples[i].scores = firstElement.examples[i].scores.map( (x) => x/length);
});
console.log(firstElement);
When to use Map
Creating new array based on doing some operation in existing array.Official Documentation
Splice
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements Official Documentation
Accept this,if it helps you.
来源:https://stackoverflow.com/questions/61794157/merging-objects-to-obtain-the-average-value-in-arrays