如何使用Underscore.js库重写此函数?

时间:2019-03-06 14:51:27

标签: javascript ecmascript-6 underscore.js

需要对此对象进行一些数据转换:

let states = [{
    "status": "up",
    "timefrom": 1551271539,
    "timeto": 1551284429
  },
  {
    "status": "down",
    "timefrom": 1551284429,
    "timeto": 1551284489
  },
  {
    "status": "up",
    "timefrom": 1551284489,
    "timeto": 1551294149
  },
  {
    "status": "down",
    "timefrom": 1551294149,
    "timeto": 1551294269
  },
  {
    "status": "up",
    "timefrom": 1551294269,
    "timeto": 1551876329
  }
]

let newStates = states.map(state => {
  let obj = {};
  obj[state.status] = [state.timefrom, state.timeto];
  return obj;
})

console.log(newStates);

我的目标是返回对象数组,其中的对象类似于{up:[1551271539,1551284429]}

2 个答案:

答案 0 :(得分:0)

使用下划线,您可以编写以下内容:

let states = [{
    "status": "up",
    "timefrom": 1551271539,
    "timeto": 1551284429
  },
  {
    "status": "down",
    "timefrom": 1551284429,
    "timeto": 1551284489
  },
  {
    "status": "up",
    "timefrom": 1551284489,
    "timeto": 1551294149
  },
  {
    "status": "down",
    "timefrom": 1551294149,
    "timeto": 1551294269
  },
  {
    "status": "up",
    "timefrom": 1551294269,
    "timeto": 1551876329
  }
]

let newStates  = _.map(states, (state) => {
  const obj = new Object();
  obj[state.status] = [state.timefrom, state.timeto];
  return obj;
})

console.log(newStates)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

与问题中的内容基本上相同,只是包裹在_.map函数中

答案 1 :(得分:0)

@nircraft的方法已经足够好了,但这也应该有所帮助。运行代码段后检查控制台。

let states = [{
    "status": "up",
    "timefrom": 1551271539,
    "timeto": 1551284429
  },
  {
    "status": "down",
    "timefrom": 1551284429,
    "timeto": 1551284489
  },
  {
    "status": "up",
    "timefrom": 1551284489,
    "timeto": 1551294149
  },
  {
    "status": "down",
    "timefrom": 1551294149,
    "timeto": 1551294269
  },
  {
    "status": "up",
    "timefrom": 1551294269,
    "timeto": 1551876329
  }
]

let newStates = [];
_.each(states, (state) => {
  if(state.status === "up") {
    var timeFrom = state.timefrom;
    var timeTo = state.timeto;
    newStates.push({up: [timeFrom, timeTo]});
  }
  else{
    var timeFrom = state.timefrom;
    var timeTo = state.timeto;
    newStates.push({down: [timeFrom, timeTo]});
  }
})

console.log(newStates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>