简体   繁体   English

转换数据的逻辑

[英]Logic to Transform data

I have an api that return me data in following format: 我有一个api,它以以下格式返回数据:

[
    {
        "_id": 1567362600000,
        "KIDate": "2019-09-02",
        "KITools": [
            {
                "data": 1,
                "tool": "A"
            },
            {
                "data": 2,
                "tool": "B"
            }
        ]
    },
    {
        "_id": 1567519839316,
        "KIDate": "2019-09-01",
        "KITools": [
            {
                "data": 2,
                "tool": "A"
            },
{
                "data": 1,
                "tool": "C"
            }
        ]
    },
    {
        "_id": 1567519839317,
        "KIDate": "2019-08-31",
        "KITools": [
            {
                "data": 0,
                "tool": "C"
            }
        ]
    },
  ]

I want to transform this data to get the following arrays: 我想转换此数据以获取以下数组:

Result 1 -  [“2019-09-02”,”2019-09-01”,”2019-08-31”]
Result 2 -  [ {name: ‘A’, data:[1, 2, 0] }, { name: 'B', data: [2, 0, 0] }, { name: 'C', data: [0, 1, 0]}]

Currently I am able to achieve this by using loops and per-defining variables with the tool name like following and looping the api data to push into this variable. 目前,我可以通过使用循环和按工具名称定义变量来实现此目的,例如跟踪并循环api数据以将其放入该变量。

var result2 = [{ name: 'A', data: [] }, { name: 'B', data: [] }, { name: 'C', data: [] }]; var result2 = [{名称:'A',数据:[]},{名称:'B',数据:[]},{名称:'C',数据:[]}];

But this is not the expected behavior, the tool names can change and I have to figure that out dynamically based on the data returned by the api. 但这不是预期的行为,工具名称可以更改,我必须根据api返回的数据来动态地弄清楚这一点。 What is the best way to achieve this without looping like crazy. 没有疯狂的循环,实现此目标的最佳方法是什么。

You could use reduce method to get the result with array of dates and object of values for each tool. 您可以使用reduce方法获取每个工具的日期数组和值对象的结果。

 const data = [{"_id":1567362600000,"KIDate":"2019-09-02","KITools":[{"data":1,"tool":"A"},{"data":2,"tool":"B"}]},{"_id":1567519839316,"KIDate":"2019-09-01","KITools":[{"data":2,"tool":"A"},{"data":1,"tool":"C"}]},{"_id":1567519839317,"KIDate":"2019-08-31","KITools":[{"data":0,"tool":"C"}]}] const result = data.reduce((r, {KIDate, KITools}, i) => { r.dates.push(KIDate); KITools.forEach(({data: dt, tool}) => { if(!r.values[tool]) r.values[tool] = Array(data.length).fill(0); r.values[tool][i] = dt }) return r; }, {dates: [], values: {}}) console.log(result) 

You can use reduce and forEach with Set and Map 您可以对SetMap使用reduceforEach

  • Initialize accumulator as object with dates and data key, dates is a Set and data is Map 使用datesdata键将累加器初始化为对象, datesSet ,数据是Map
  • For every element add the KIDate to dates key, 对于每个元素,将KIDate添加到日期键,
  • Loop over KITools , check if that particular too exists in data Map if it exists update it's value by adding current values to id, if not set it's value as per current values 遍历KITools ,检查该数据Map是否也存在该特定KITools ,如果存在,则通过将当前值添加到id来更新其值;如果未按照当前值设置其值

 let data = [{"_id": 1567362600000,"KIDate": "2019-09-02","KITools": [{"data": 1,"tool": "A"},{"data": 2,"tool": "B"}]},{"_id": 1567519839316,"KIDate": "2019-09-01","KITools": [{"data": 2,"tool": "A"},{"data": 1,"tool": "C"}]},{"_id": 1567519839317,"KIDate": "2019-08-31","KITools": [{"data": 0,"tool": "C"}]},] let final = data.reduce((op,{KIDate,KITools})=>{ op.dates.add(KIDate) KITools.forEach(({data,tool})=>{ if(op.data.has(data)){ op.data.get(data).data.push(tool) } else{ op.data.set(data, {name: data, data:[tool]}) } }) return op },{dates:new Set(),data: new Map()}) console.log([...final.dates.values()]) console.log([...final.data.values()]) 

The result1 array can be obtained via a direct .map() . 可以通过直接.map()获得result1数组。 To build the result2 array will require additional work - one approach would be to do so via .reduce() as detailed below: 要构建result2数组将需要额外的工作-一种方法是通过.reduce() ,如下所示:

 const data=[{"_id":1567362600000,"KIDate":"2019-09-02","KITools":[{"data":1,"tool":"A"},{"data":2,"tool":"B"}]},{"_id":1567519839316,"KIDate":"2019-09-01","KITools":[{"data":2,"tool":"A"},{"data":1,"tool":"C"}]},{"_id":1567519839317,"KIDate":"2019-08-31","KITools":[{"data":0,"tool":"C"}]}]; const result1 = data.map(item => item.KIDate); const result2 = data.reduce((result, item) => { item.KITools.forEach(kitool => { /* For current item, search for matching tool on name/tool fields */ let foundTool = result.find(i => i.name === kitool.tool); if (foundTool) { /* Add data to data sub array if match found */ foundTool.data.push(kitool.data); } else { /* Add new tool if no match found and init name and data array */ result.push({ name: kitool.tool, data: [kitool.data] }); } }); return result; }, []).map((item, i, arr) => { /* Second phase of processing here to pad the data arrays with 0 values if needed */ for (let i = item.data.length; i < arr.length; i++) { item.data.push(0); } return item; }); console.log('result1:', result1); console.log('result2:', result2); 

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

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