对象的平面数组到嵌套对象或Map

时间:2015-03-22 09:09:33

标签: javascript data-structures functional-programming

我尝试转换这个对象数组

[{
property1: 10,
property2: 11,
timestamp: date1,
value: 2
},{
    property1: 10,
    property2: 11,
    timestamp: date2,
    value: 8
},{
    property1: 10,
    property2: 14,
    timestamp: date2,
    value: 3
}, {
    property1: 17,
    property2: 11,
    timestamp: date3,
    value: 4
}
]

进入这个

{
  10 : {
    11 : {
      date1 : 2,
      date2 : 8
    },
    14 : {
      date2 : 3
    }
  },
  17 : {
    11 : {
      date3 : 4
    }
  }
}

如您所见,第一个示例是一个平面对象数组,我使用属性将嵌套对象映射到属性值。

我想出了一个像这样的forEach方法:

var mappedData = {};
rawData.forEach((sample) => {

if (!mappedData[sample.property1]) {
    mappedData[sample.property1] = {};
}

if (!mappedData[sample.property1][sample.property2]) {
    mappedData[sample.property1][sample.property2] = new Map();
}

mappedData[sample.property1][sample.property2].set(timestamp, sample.value);

});

但我想用更多功能编程风格来做这件事......也许还有一个减少......

1 个答案:

答案 0 :(得分:0)

var aggregateTreeFromObjectList = function (collector, item) {
  var
    firstLevelId    = item.property1,
    secondLevelId   = item.property2,

    firstLevelNode  = collector[firstLevelId] || (collector[firstLevelId] = {}),
    secondLevelNode = firstLevelNode[secondLevelId] || (firstLevelNode[secondLevelId] = {})
  ;
  secondLevelNode[item.timestamp] = item.value;

  return collector;
};

var list = [{
  property1: 10,
  property2: 11,
  timestamp: "date-001",
  value: 2
}, {
  property1: 10,
  property2: 11,
  timestamp: "date-002",
  value: 8
}, {
  property1: 10,
  property2: 14,
  timestamp: "date-002",
  value: 3
}, {
  property1: 17,
  property2: 11,
  timestamp: "date-003",
  value: 4
}];

var map = list.reduce(aggregateTreeFromObjectList, {});

console.log(map);