lodash分配键值对

时间:2017-04-11 19:14:52

标签: javascript node.js lodash vuejs2

如何改变这个

[ { '1491926400000': 222 }, { '1491926400000': 489 } ]

到此:

[ { date: '1491926400000', count: 222 }, { date: '1491926400000', count: 489 } ]

我尝试过' reduce'和'转换'使用lodash但不随身携带。

3 个答案:

答案 0 :(得分:0)

var oldArray = [ { '1491926400000': 222 }, { '1491926400000': 489 } ];
var newArray = [];
for(var i = 0; i < oldArray.length; i++){
  var originObject = oldArray[i];
  for(var key in originObject) {
    var value = originObject[key];
    var obj = {date: key, count: value};
    newArray.push(obj);
  }
}

进行转换

答案 1 :(得分:0)

使用Array#map的可能解决方案。

var arr = [{ '1491926400000': 222 }, { '1491926400000': 489 }],
    res = arr.map(v => Object.assign({}, ...Object.keys(v).map(c => ({ date: c, count: v[c]}))));
    
    console.log(res);

答案 2 :(得分:0)

这是一个使用lodash/fp(curried函数/数据最后)的简洁解决方案:

const mapData = map(
  flowRight(
    zipObject(['date', 'count']),   // { date: '1491926400000', count: 222 }
    flatten,                        // ['1491926400000', 222]
    toPairs                         // [ ['1491926400000', 222] ]
  )
)

常规lodash中的相同内容:

const mapData = (data) => map(data, (o) =>
  zipObject(['date', 'count'], flatten(toPairs(o)))
)

用于:

mapData([ { '1491926400000': 222 }, { '1491926400000': 489 } ])

// [ { date: '1491926400000', count: 222 }, { date: '1491926400000', count: 489 } ]