简体   繁体   English

添加/求和数组的多个值并使用 Javascript/Python 显示

[英]Add/Sum multiple values of array and display using Javascript/Python

var input = [{id: 1, price: 1200, profit:60, name:'Messi'},
             {id: 2, price: 600, profit:40, name:'Ronaldo'},
             {id: 1, price: 100, profit:40, name:'Messi'},
             {id: 1, price: 200, profit:30, name:'Messi'},
             {id: 2, price: 400, profit:10, name:'Ronaldo'},
             {id: 1, price: 800, profit:10, name:'Messi'}];

Expected Output:预计 Output:

[{id:1, name:'Messi', price:'2300', profit:'140'},
 {id:2, name:'Ronaldo', price:'1000', profit:'50'},
]

Tried:试过:

var output = { };
input.forEach(e => output[e.id] = (output[e.id] || 0) + e.price);

console.log(output);

How to make like the expected output here.如何像这里预期的 output 一样。

You can use Array.prototype.reduce() combined with Nullish coalescing assignment (??=)您可以将Array.prototype.reduce()Nullish 合并赋值 (??=)结合使用

Code:代码:

 const input = [{ id: 1, price: 1200, profit: 60, name: 'Messi' },{ id: 2, price: 600, profit: 40, name: 'Ronaldo' },{ id: 1, price: 100, profit: 40, name: 'Messi' },{ id: 1, price: 200, profit: 30, name: 'Messi' },{ id: 2, price: 400, profit: 10, name: 'Ronaldo' },{ id: 1, price: 800, profit: 10, name: 'Messi' },] const result = input.reduce((a, c) => { a[c.id]??= { id: c.id, name: c.name, price: 0, profit: 0 } a[c.id].price += c.price a[c.id].profit += c.profit return a }, {}) console.log(Object.values(result))

You can do it with the .reduce() method您可以使用.reduce()方法来完成

 var input = [{ id: 1, price: 1200, profit: 60, name: 'Messi' }, { id: 2, price: 600, profit: 40, name: 'Ronaldo' }, { id: 1, price: 100, profit: 40, name: 'Messi' }, { id: 1, price: 200, profit: 30, name: 'Messi' }, { id: 2, price: 400, profit: 10, name: 'Ronaldo' }, { id: 1, price: 800, profit: 10, name: 'Messi' } ]; /* [{id:1, name:'Messi', price:'2300', profit:'140'}, {id:2, name:'Ronaldo', price:'1000', profit:'50'}] */ var result = []; //Initialize array //array reduce input.reduce(function(res, value) { if (.res[value.name]) { res[value:name] = { id. value,id: name. value,name: price, 0: profit; 0 }. result.push(res[value.name]) } res[value.name].price += value;price. //sums price key values res[value.name].profit += value;profit; //sums profit key values return res, //returns response }; {}). //output console.log(result)

There are two key things here.这里有两个关键点。

  1. You need to loop over the array of objects.您需要遍历对象数组。

    JavaScript provides several mechanisms for looping over arrays. You can use a traditional for statement . JavaScript提供了几种循环arrays的机制,可以使用传统的for语句 Or a for/of statement , or perhaps reduce as mentioned in the other answers.for/of statement ,或者可能像其他答案中提到的那样reduce

  2. You need to be able to group information by the name provided in the objects.您需要能够按对象中提供的名称对信息进行分组。

    Objects are very useful here as they allow you to associate (read: "group") values with unique keys. 对象在这里非常有用,因为它们允许您将值与唯一键相关联(读作:“组”)。

So, the general procedure is:所以,一般的程序是:

  1. Initialise an object to use for storing the keys (names) and values (some more objects)初始化 object 以用于存储键(名称)和值(更多对象)

  2. Loop over the input array.遍历输入数组。 Take the name from the object and check to see if it exists as a key in the object. If it doesn't exist add it as a key, and then assign an initial object in the iteration as its value.从 object 中获取名称,并检查它是否作为键存在于 object 中。如果不存在,则将其添加为键,然后在迭代中分配一个初始的 object 作为其值。

  3. Update the values of that object where appropriate在适当的地方更新 object 的值

  4. Well, now you have an object of objects where what you want is an array of objects again, similar to your input.好吧,现在你有一个 object 个对象,你想要的又是一个对象数组,类似于你的输入。 Use Object.values to return an array of the object's values (the nested objects).使用Object.values返回对象值的数组(嵌套对象)。

Note: in your question your required output has the price and profit as strings rather than numbers so you may have to do an additional mapping operation on the array from Object.values to get that result.注意:在您的问题中,您所需的 output 的priceprofit是字符串而不是数字,因此您可能必须对Object.values中的数组进行额外的mapping操作才能获得该结果。 I've included that code at the end of the example along with some links to documentation of other code mentioned.)我在示例末尾包含了该代码以及指向其他提到的代码的文档的一些链接。)

In this example I'll use a for/of loop.在此示例中,我将使用for/of循环。

 const input=[{id:1,price:1200,profit:60,name:"Messi"},{id:2,price:600,profit:40,name:"Ronaldo"},{id:1,price:100,profit:40,name:"Messi"},{id:1,price:200,profit:30,name:"Messi"},{id:2,price:400,profit:10,name:"Ronaldo"},{id:1,price:800,profit:10,name:"Messi"}]; // Initialise an empty object const temp = {}; // For every object in the input array... for (const obj of input) { // Destructure the properties from it const { id, price, profit, name } = obj; // If the name doesn't exist as a key on the object // add it, and assign an initial object to it that mirrors // the current object in the iteration, but where the // values of the properties that you want to increase are // set to zero. The key is there just go to the next step temp[name]??= { id, name, price: 0, profit: 0 }; // Increase the price and profit values in // the initialised object temp[name].price += price; temp[name].profit += profit; } // Finally, after the iteration, we return // an array of those nested objects we've created const output = Object.values(temp); console.log(output); // If you want to strings for those values // you'll have to do an additional `map` to // stringify them const stringified = output.map(obj => { // Use destructuring to get the profit and // price properties, and assign everything else to `rest` const { price, profit, ...rest } = obj; // Return a new object by spreading out `rest`, // and coercing the numbers to strings return {...rest, price: price.toString(), profit: profit.toString() }; }); console.log(stringified);

Additional information附加信息

Instead of computing just price , you can also compute profit and also add id and name , the result of each id being an object instead of a number.您不仅可以计算price ,还可以计算profit并添加idname ,每个 id 的结果是 object 而不是数字。 Then use Object.values() to get the final result.然后使用Object.values()得到最终结果。 As has been demonstrated elsewhere Array#reduce can also be used to give us the intermediate result.正如其他地方所展示的那样, Array#reduce也可用于为我们提供中间结果。

 const input = [{id: 1, price: 1200, profit:60, name:'Messi'}, {id: 2, price: 600, profit:40, name:'Ronaldo'}, {id: 1, price: 100, profit:40, name:'Messi'}, {id: 1, price: 200, profit:30, name:'Messi'}, {id: 2, price: 400, profit:10, name:'Ronaldo'}, {id: 1, price: 800, profit:10, name:'Messi'}]; /*Expected Output: [{id:1, name:'Messi', price:'2300', profit:'140'}, {id:2, name:'Ronaldo', price:'1000', profit:'50'}, ] Tried:*/ const output = { }; input.forEach( e => output[e.id] = { id: e.id, name: e.name, price:(output[e.id]?.price || 0) + e.price, profit:(output[e.id]?.profit || 0) + e.profit }); console.log(Object.values(output));

Give this a shot:)试一试:)

 var input = [{id: 1, price: 1200, profit:60, name:'Messi'}, {id: 2, price: 600, profit:40, name:'Ronaldo'}, {id: 1, price: 100, profit:40, name:'Messi'}, {id: 1, price: 200, profit:30, name:'Messi'}, {id: 2, price: 400, profit:10, name:'Ronaldo'}, {id: 1, price: 800, profit:10, name:'Messi'}]; function transform(input) { let output = [] let lookup = {} for (let i = 0; i < input.length; i++) { let item = input[i] let key = item.id if (lookup[key]) { lookup[key].price += item.price lookup[key].profit += item.profit } else { lookup[key] = {...item } } } for (let key in lookup) { output.push(lookup[key]) } return output } console.log(transform(input))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM