在Javascript中过滤和引用数组到对象数组

时间:2017-02-21 03:49:04

标签: javascript arrays filter lodash

我有2个阵列:

时间戳阵列:

var timeStamp = [["0:00","1:00"], ["2:00","3:00"]];

时间标签参考:

var timeLabels = [
 { name: "0:00", present: true, label: ["0:00", "1:00"], alterName:"" }, 
 { name: "1:00", present: true, label: ["1:00", "2:00"], alterName:"" }, 
 { name: "2:00", present: true, label: ["2:00", "3:00"], alterName:"" }]

我想使用Lodash来过滤TimeStamp数组,但我想要的方法是对象数组所独有的。我目前有一个for循环,它不是很优雅。

最终,我想创建一个TimeLabels对象数组,如果时间存在于timeStamp的present中,则first index字段设置为True或False。

参考上面的时间戳数组,结果将是:

var timeResult = [
 { name: "0:00", present: true, label: ["0:00", "1:00"], alterName:"" }, 
 { name: "1:00", present: false, label: ["1:00", "2:00"], alterName:"" }, 
 { name: "2:00", present: true, label: ["2:00", "3:00"], alterName:"" }]

我更习惯使用lodash,但我想知道其他方法是否会更好地构建解决方案,或者我正在使用的for循环是否正常。

3 个答案:

答案 0 :(得分:1)

timeLabels内的Foreach elment使用indexOf确定label中是否存在timestamp。要使用indexOf,您必须使用{{1}将对象转换为字符串}}。



JSON.stringify()




答案 1 :(得分:1)

我们可以使用map来迭代并返回每个已转换的item。请注意,我使用assign而不是手动分配present属性,这是为了避免改变timeLabels集合中的对象。最后,我们使用intersectionWithisEmpty()的组合来获取present值(请注意,结果值被否定)。

var timeResult = _.map(timeLabels, function(item) {
  return _.assign({}, item, {
    present: !_(timeStamp)
      .intersectionWith([item.label], _.isEqual)
      .isEmpty()
  });
});

var timeStamp = [
  ["0:00", "1:00"],
  ["2:00", "3:00"]
];

var timeLabels = [{
    name: "0:00",
    present: true,
    label: ["0:00", "1:00"],
    alterName: ""
  },
  {
    name: "1:00",
    present: true,
    label: ["1:00", "2:00"],
    alterName: ""
  },
  {
    name: "2:00",
    present: true,
    label: ["2:00", "3:00"],
    alterName: ""
  }
];

var timeResult = _.map(timeLabels, function(item) {
  return _.assign({}, item, {
    present: !_(timeStamp)
      .intersectionWith([item.label], _.isEqual)
      .isEmpty()
  });
});

console.log(timeResult);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

答案 2 :(得分:0)

var tmpTimeStamp = timeStamp.map(function(ts){ return ts[0]+"_"+ts[1] });
timeResult = timeResult.map(function(t){
  t.present = tmpTimeStamp.indexOf(t.label[0]+"_"+t.label[1]) > -1;
  return t;
});