Javascript:根据属性值将对象数组拆分为具有动态名称的单独数组 [英] Javascript: Split array of objects into seperate arrays with dynamic names depending on property value

查看:85
本文介绍了Javascript:根据属性值将对象数组拆分为具有动态名称的单独数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含对象的数组.现在,我想将数组切片为仅包含那些与某个属性值匹配的对象的新数组.

I have an array containing objects. Now I want to slice the array to new arrays containing only those objects matching a certain property value.

理想情况下,应该动态创建新的数组名称.

Ideally the new array names should be created dynamically.

原始数组如下:

specificSlotButtonArray = [
  {slotStarttime:"06:00:00", slotTimespan:1},
  {slotStarttime:"09:00:00", slotTimespan:1},
  {slotStarttime:"12:00:00", slotTimespan:2},
  {slotStarttime:"15:00:00", slotTimespan:2},
  {slotStarttime:"18:00:00", slotTimespan:3}
];

新数组应如下所示:

timespan1 = [
  {slotStarttime:"06:00:00", slotTimespan:1},
  {slotStarttime:"09:00:00", slotTimespan:1}
]

timespan2 = [
  {slotStarttime:"12:00:00", slotTimespan:2},
  {slotStarttime:"15:00:00", slotTimespan:2}
]

timespan3 = [
  {slotStarttime:"18:00:00", slotTimespan:3}
]

如果可能的话,我想避免IE和其他一些较旧的浏览器不支持的javascript语法/函数.

If possible, I want to avoid javascript syntax / functions, which are not supported by IE and some other older browsers.

我已经尝试使用 reduce() slice(),但是没有找到解决方案.

I already tried to work with reduce() and slice(), but did not find a solution.

推荐答案

您可以使用 reduce 轻松实现所需的结果,因为您可以使用 reduce 生成对象,这是一个如何做的例子.

You can simply achieve your desired outcome using reduce, as you can produce an object using reduce, here's an example of how you could do it.

如您所见,它将检查对象上的相关属性是否不为null,如果为null,则将其设置为空数组,执行此检查后,将相关值简单地推送到数组,像这样.

As you can see, it'll check that the relevant property on the object isn't null, if it is, then it's set to an empty array, after this check, it's safe to simply push the relevant values onto the array, like so.

var array = [{
    slotStarttime: "06:00:00",
    slotTimespan: 1
  },
  {
    slotStarttime: "09:00:00",
    slotTimespan: 1
  },
  {
    slotStarttime: "12:00:00",
    slotTimespan: 2
  },
  {
    slotStarttime: "15:00:00",
    slotTimespan: 2
  },
  {
    slotStarttime: "18:00:00",
    slotTimespan: 3
  }
];

var newObject = array.reduce(function(obj, value) {
  var key = `timespan${value.slotTimespan}`;
  if (obj[key] == null) obj[key] = [];

  obj[key].push(value);
  return obj;
}, {});

console.log(newObject);

这篇关于Javascript:根据属性值将对象数组拆分为具有动态名称的单独数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆