【问题标题】:Javascript: Split array of objects into seperate arrays with dynamic names depending on property valueJavascript:根据属性值将对象数组拆分为具有动态名称的单独数组
【发布时间】:2019-05-29 06:01:26
【问题描述】:

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

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

原始数组如下所示:

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 语法/函数。

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

【问题讨论】:

    标签: javascript arrays object slice


    【解决方案1】:

    以下解决方案使用Array.reducespecificSlotButtonArray 上迭代一次。此解决方案将适应任意数量的slotTimespan

    const 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,
      },
    ];
    
    // Loop through the array
    const splitted = specificSlotButtonArray.reduce((tmp, x) => {
      // Look if we got already an array having the slotTimespan of the current
      // item to treat
      const match = tmp.find(y => y.some(z => z.slotTimespan === x.slotTimespan));
    
      // If we have such array, push the data into it
      if (match) {
        match.push(x);
      } else {
        // If we don't create a new array
        tmp.push([x]);
      }
    
      return tmp;
    }, []);
    
    console.log(splitted);

    如果你想在Array.reduce 之后直接处理数组,你可以使用解构:

    const [
      timespan1,
      timespan2,
      timespan3
    ] = specificSlotButtonArray.reduce((tmp, x) => {
    

    【讨论】:

      【解决方案2】:

      使用一个通用的分组键reducer。我将从previous answer of mine 获取它。这是一种优雅而简单的方法,可以生成一个函数,该函数按作为参数的特定键对数据进行分组。

      const groupBy = key => (result,current) => {
        const item = Object.assign({},current);
        if (typeof result[current[key]] == 'undefined'){
          result[current[key]] = [item];
        }else{
          result[current[key]].push(item);
        }
        return result;
      };
      
      const 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}
      ];
      
      const timespan = specificSlotButtonArray.reduce(groupBy('slotTimespan'),{});
      console.log(timespan);

      【讨论】:

        【解决方案3】:

        您可以使用此函数创建按slotTimespan 分组的单独数组,

            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}
            ];
            
            function groupBy(arr, property) {
                return arr.reduce(function(memo, x) {
                    if (!memo[x[property]]) { memo[x[property]] = []; }
                    memo[x[property]].push(x);
                    return memo;
                }, {});
            }
            
            console.log(groupBy(specificSlotButtonArray, "slotTimespan"));

        【讨论】:

          【解决方案4】:

          您可以通过为零件数组获取一个对象来减少数组。

          var 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 = [],
              timespan2 = [],
              timespan3 = [];
              
          specificSlotButtonArray.reduce(function (r, o) {
              r[o.slotTimespan].push(o);
              return r;
          }, { 1: timespan1, 2: timespan2, 3: timespan3 });
          
          console.log(timespan1);
          console.log(timespan2);
          console.log(timespan3);
          .as-console-wrapper { max-height: 100% !important; top: 0; }

          【讨论】:

            【解决方案5】:

            您可以使用reduce 简单地实现您想要的结果,因为您可以使用reduce 生成一个对象,这里有一个示例说明如何做到这一点。

            如您所见,它会检查对象上的相关属性是否为空,如果是,则将其设置为空数组,在此检查之后,只需将相关值推送到数组,像这样。

            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);

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-10-07
              • 1970-01-01
              • 2013-01-19
              • 2018-07-30
              • 2020-11-20
              • 2022-01-18
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多