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

js81xvg6  于 2023-01-08  发布在  Java
关注(0)|答案(5)|浏览(140)
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 output = { };
input.forEach(e => output[e.id] = (output[e.id] || 0) + e.price);

console.log(output);

如何使这里像预期的输出。

q9yhzks0

q9yhzks01#

您可以使用.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)
uurv41yg

uurv41yg2#

您可以将Array.prototype.reduce()Nullish coalescing assignment (??=)结合使用
代码:

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

fkaflof63#

这里有两个关键问题。
1.您需要循环遍历对象数组。
JavaScript提供了几种循环数组的机制,你可以使用传统的for语句,或者for/of语句,或者reduce,就像前面提到的那样。
1.您需要能够按对象中提供的名称对信息进行分组。
Objects are very useful,因为它们允许您进行关联(请阅读:"group")具有唯一键的值。
因此,一般程序是:
1.初始化一个用于存储键(名称)和值(更多对象)的对象
1.循环遍历输入数组,从对象中获取名称,检查它是否作为键存在于对象中,如果不存在,则将其添加为键,然后在迭代中分配初始对象作为其值。
1.根据需要更新该对象的值
1.好了,现在你有了一个对象的对象,你想要的是一个对象数组,类似于你的输入,使用Object.values返回一个对象值数组(嵌套对象)。
注意:在你的问题中,你需要的输出是字符串形式的priceprofit,而不是数字形式的,所以你可能需要对Object.values中的数组执行额外的mapping操作才能得到这个结果。我在示例的结尾包含了这些代码,并提供了一些链接,指向其他提到的代码的文档。)
在这个例子中,我将使用一个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);

补充资料

nbnkbykc

nbnkbykc4#

除了计算price之外,你还可以计算profit,并将idname相加,每个id的结果是一个对象而不是一个数字,然后使用Object.values()来得到最终结果,正如在其他地方所演示的,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));
wkyowqbh

wkyowqbh5#

给予这个:)

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

相关问题