如何基于动态键创建嵌套对象

时间:2019-05-09 16:28:44

标签: javascript arrays

我需要将一些数据转换为特殊格式。棘手的部分是,它需要通过动态键进行分组和嵌套。由于原始数据是平坦的。

以下是一些简化的示例数据:

const data = [
  {
    category: 'Classic',
    price: 1,
    order: '1233-ABC'
    currency: 'EUR',
  },
  {
    category: 'Classic',
    price: 2,
    order: '1234-ABC'
    currency: 'EUR',
  },
  {
    category: 'Modern',
    price: 3,
    order: '1235-ABC'
    currency: 'USD',
  },
  {
    category: 'Classic',
    price: 4,
    order: '1236-ABC'
    currency: 'EUR',
  },
  {
    category: 'Modern',
    price: 5,
    order: '1237-ABC'
    currency: 'EUR',
  },
  {
    category: 'Classic',
    price: 6,
    order: '1238-ABC'
    currency: 'USD',
  },
  {
    category: 'Modern',
    price: 7,
    order: '1239-ABC'
    currency: 'USD',
  }
];

现在,我想定义分组和聚合。

例如:

grouping = ['category'];
sum = ['price'];

因此,应按category键进行分组,并对所有price键条目进行汇总。

//预期输出

[{
    category: 'Classic',
    price: 13
}, {
    category: 'Modern',
    price: 15
}]

我可以通过reduce来解决这个问题。

代码如下:

let groupingsField = ['category'];
let aggregateField = ['price']

let [group, ...rest] = groupingsField
let [sum, ...noone] = aggregateField

const groupedData = data.reduce((acc, current) => {
  acc.push({
    [group]: current[group],
    [sum]: data.filter(item => item[group] === current[group])
    .map(el => el[sum])
    .reduce((total, current) => total + current)
  })

  return acc
}, [])
.reduce((acc, current) => {
  const x = acc.find(item => item[group] === current[group])

  return !x ? acc.concat([current]) : acc
}, [])

但是,我需要分组是动态的,并且如果那里存在大于1的值,它应该创建嵌套的sub数据集。应该可以添加多个分组。

//示例2

grouping = ['category', 'currency'];
sum = ['price'];

//预期输出

[{
    category: 'Classic',
    price: 13,
    sub: [{
        currency: 'EUR',
        price: 7
    }, {
        currency: 'USD',
        price: 6
    }]
}, {
    category: 'Modern',
    price: 15,
    sub: [{
        currency: 'EUR',
        price: 9
    }, {
        currency: 'USD',
        price: 10
    }]
}]

因此,如果我要向分组添加另一个键

grouping = ['category', 'currency', 'something'];

应该是三个层次的深层嵌套。

{
 category: 'Modern',
 price: 15,
 sub: [{
   currency: 'EUR',
   price: 9,
   sub: [{
     someting: ...
     price: ...
   }]
 }]
}

但是,我无法理解如何基于groupings动态添加嵌套。我想我需要在这里递归。

希望在此方面有所帮助!

2 个答案:

答案 0 :(得分:1)

感谢您的帮助! 但是,经过一番睡眠,我想出了自己的解决方案:


groups = ['category', 'currency']; // this can be dynamic 
sum = ['price'];

function createGroup (groups, data, sum, childNode = 'sub') {
    let [primaryGroup, ...rest] = groups;

    let groupedData = data.reduce((acc, current) => {
    let chunk = {
        [primaryGroup]: current[primaryGroup],
        [sum]: data.filter(item => item[primaryGroup] === current[primaryGroup])
        .map(el => el[sum])
        .reduce((total, current) => total + current),
       ...(rest.length > 0 ? {[childNode]: createGroup(rest, data)} : {})
    }

    acc.push(chunk)
    return acc
  }, [])
    .reduce((acc, current) => {
        const x = acc.find(item => item[primaryGroup] === current[primaryGroup])
        return !x ? acc.concat([current]) : acc
    }, [])

  return groupedData;
}

答案 1 :(得分:0)

嗯……这确实是一个挑战,但我认为它正在起作用……也许不是以最花哨的方式,但我想它会做到的。

var newArr = [];
var MyObj = {};
var MyObj2 = {};


    for( i = 0; i < data.length; i++){
        if (data[i].category + '|' + data[i].currency in MyObj) MyObj[data[i].category + '|' + data[i].currency] += data[i].price;
        else MyObj[data[i].category + '|' + data[i].currency] = data[i].price;
    }

    for (var key in MyObj) {
        let keyArr=-1;
        let split_key = key.split("|");


        for( i = 0; i < newArr.length; i++){
            console.log(newArr[i].category + '/' +split_key[0] + i);
            if (newArr[i].category == split_key[0]) {

                keyArr=i;
                break;
            }
        }

    if (keyArr<0){
        MyObj2['category'] = split_key[0];
        MyObj2['price'] = MyObj[key];
        MyObj2['sub'] = [{currency: split_key[1], price: MyObj[key]}];
        newArr.push(MyObj2);
    }else{
        newArr[keyArr]['price']+=MyObj[key];
        newArr[keyArr]['sub'].push({currency: split_key[1], price: MyObj[key]});
    }

        MyObj2={};

    }
    console.log(newArr);