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)
ask by v2103 translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…