简体   繁体   English

在 reduce 函数中使用函数参数:Javascript

[英]Use function argument inside reduce function : Javascript

I have an array of objects with the following structure that is being sent as response:我有一组具有以下结构的对象作为响应发送:


    let sampleData = [
      { valueObj: { High: 4, Low: 5,  Medium: 7 } , time: "1571372233234" , sum: 16 },
      { valueObj: { High: 5, Low: 3, Medium : 1 }, time: "1571372233234" , sum: 9},
      { time: "14354545454", sum: 0},
      { time: "14354545454", sum: 0} }
    ];


I need to take each key within each object inside array and form an array out of it.我需要获取数组内每个对象中的每个键并从中形成一个数组。 Basically grouping based on the key present in all the objects.If the object has no "values" it should return 0 across the val1,val2,val3.基本上基于所有对象中存在的键进行分组。如果对象没有“值”,它应该在 val1、val2、val3 中返回 0。

result = [
  { name: 'High', data: [4, 5, 0, 0] }, 
  { name: 'Medium', data: [5, 3, 0, 0] }, 
  { name: 'Low', data: [7, 1, 0, 0] }
]

Just want to pass an argument to a function, that should be used inside reduce.只是想将一个参数传递给一个函数,应该在 reduce 中使用。 Here I am passing "valueObj" and that should be used inside reduce.在这里,我传递了“valueObj”,应该在reduce 中使用它。 But I am unable to refer the same inside reduce但是我无法在reduce里面引用相同的内容

I have tried the following:我尝试了以下方法:

 let sampleData = [{ valueObj: { High: 4, Low: 5, Medium: 7 }, time: "1571372233234", sum: 16 }, { valueObj: { High: 5, Low: 3, Medium : 1 }, time: "1571372233234", sum: 9 }, { time: "14354545454", sum: 0 }, { time: "14354545454", sum: 0 }]; let keys = ['High', 'Low', 'Medium']; function formResult(sampleData, values, keys){ let grouped = sampleData.reduce((r, { values = {} } = {}) => { r.forEach(({ name, data }) => data.push(values[name] || 0)); return r; }, keys.map(name => ({ name, data: [] }))); console.log(grouped); } formResult(sampleData,"valueObj", keys)

Rename the values param (I've used prop ) since it's used in the reduce function.重命名values参数(我使用过prop ),因为它在 reduce 函数中使用。 Use destructuring with computed properties to extract the property and assign it to values :使用具有计算属性的解构来提取属性并将其分配给values

 const sampleData = [{ valueObj: { High: 4, Low: 5, Medium: 7 }, time: "1571372233234", sum: 16 }, { valueObj: { High: 5, Low: 3, Medium : 1 }, time: "1571372233234", sum: 9 }, { time: "14354545454", sum: 0 }, { time: "14354545454", sum: 0 }]; const keys = ['High', 'Low', 'Medium']; function formResult(sampleData, prop, keys){ let grouped = sampleData.reduce((r, { [prop]: values = {} } = {}) => { r.forEach(({ name, data }) => data.push(values[name] || 0)); return r; }, keys.map(name => ({ name, data: [] }))); console.log(grouped); } formResult(sampleData,"valueObj", keys);

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

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