代码之家  ›  专栏  ›  技术社区  ›  Austin

如何将数组转换为每个键具有特定名称的javascript对象

  •  1
  • Austin  · 技术社区  · 6 年前

    我正在尝试使用javascript将下面的数组转换成一个javascript对象,但我不知道该怎么做。

    这是我的输入数组。对于这个数组,每个键代表一周中的一天(星期日到星期六)。所以键0=星期日,键1=星期一…一直到键6,它=星期六。

    var times = [["8:30-12:00","14:00-18:00"],
    ["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],
    ["9:00-21:00"],[],[]];
    

    这是我要转换的javascript对象 times 数组到:

    timeObj = {
      sunday: [
        {
          start: '08:30',
          stop: '12:00'
        },
        {
          start: '14:00',
          stop: '18:00'
        }
      ],
      monday: [
        {
          start: '06:15',
          stop: '9:30'
        },
        {
          start: '13:00',
          stop: '16:00'
        },
        {
          start: '20:00',
          stop: '23:15'
        }
      ],
      tuesday: [],
      wednesday: [
        {
           start: '9:00',
           stop: '21:00'
        }
      ],
      thursday:  [
        {
           start: '9:00',
           stop: '21:00'
        }
      ],
      friday:  [],
      saturday:  []
    };
    

    转换数组的最佳方法是什么 时代 进入对象 timeObj ?

    4 回复  |  直到 6 年前
        1
  •  2
  •   stevendesu    6 年前

      • 0 -> sunday 1 -> monday
      • 0 -> start 1 -> end
    • "8:30-12:00" ["08:30", "12:00"]

    var arr = [1, 2, 3, 4, 5, 6, 7];
    var obj = {
        sunday: arr[0],
        monday: arr[1],
        tuesday: arr[2],
        ...
    }
    

    var arr = [1, 2, 3, 4, 5, 6, 7];
    var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
    var obj = {};
    for (var i = 0; i < days.length; i++)
    {
        obj[days[i]] = arr[i];
    }
    

    reduce

    function( accumulator, element, index ) {
        // ...
    }
    

    var arr = [1, 2, 3, 4, 5, 6, 7];
    // arr.reduce(myFunction, 0):
    var _accumulator = 0;
    for (var _i = 0; _i < arr.length; _i++)
    {
        _accumulator = myFunction(_accumulator, arr[_i], _i);
    }
    

    var arr = [1, 2, 3, 4, 5, 6, 7];
    var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
    var _accumulator = {};
    for (var _i = 0; _i < arr.length; _i++)
    {
        _accumulator = (
            // Some function that returns _accumulator, but
            // with the days[_i] key set to arr[_i]
        );
    }
    

    // Some function that returns _accumulator, but
    // with the days[_i] key set to arr[_i]
    function setKeyValue(_accumulator, _i)
    {
        _accumulator[days[_i]] = arr[_i];
        return _accumulator;
    }
    

    Array.reduce

    var arr = [1, 2, 3, 4, 5, 6, 7];
    var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
    var obj = arr.reduce(
        function(acc, el, idx)
        {
            acc[days[idx]] = arr[idx];
            return acc;
        },
        // The initial value:
        {}
    );
    

    {start: "08:30", end: "12:00"}

    "8:30+12:00" "8:30-12:00-2:00"

    split

    var str = "8:30-12:00";
    var arr = str.split("-");
    console.log(arr);
    // Outputs: ["8:30", "12:00"]
    

    var arr = str.split("-");
    var obj = {
        start: arr[0],
        end: arr[1]
    };
    

    08:30 8:30

    var str = "12:30"; // 12:30
    str = "0" + str; // 012:30
    // Grab the last 5 characters
    str = str.substr(-5); // 12:30 (again)
    

    0

    var arr = str.split("-");
    var obj = {
        start: ("0" + arr[0]).substr(-5),
        end: ("0" + arr[1]).substr(-5)
    };
    

    var arr = ["8:30-12:00", "14:00-18:00"];
    var parsedArr = [];
    for (var i = 0; i < arr.length; i++)
    {
        var splitStr = arr[i].split("-");
        parsedArr[i] = {
            start: ("0" + splitStr[0]).substr(-5),
            end: ("0" + splitStr[1]).substr(-5)
        }
    }
    

    map

    var arr = ["8:30-12:00", "14:00-18:00"];
    var parsedArr = arr.map(function(el)
    {
        var splitStr = el.split("-");
        return {
            start: ("0" + splitStr[0]).substr(-5),
            end: ("0" + splitStr[1]).substr(-5)
        };
    });
    

    var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
    var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
    
    var timeObj = {};
    
    for (var i = 0; i < times.length; i++)
    {
        // Create an empty array:
        timeObj[days[i]] = [];
    
        // For each timespan in the original array, add it to this day
        for (var j = 0; j < times[i].length; j++)
        {
            var timespan = times[i][j];
    
            // Parse the string
            var timespanArr = timespan.split("-");
            var timespanObj = {
                start: ("0" + timespanArr[0]).substr(-5),
                end: ("0" + timespanArr[1]).substr(-5)
            };
    
            // Append
            timeObj[days[i]].push(timespanObj);
        }
    }
    
    console.log(timeObj);
    

    var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
    var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
    var obj = times.reduce(function(acc, el, idx)
    {
        acc[days[idx]] = el.map(function(timespan)
        {
            var splitStr = timespan.split("-");
            return {
                start: ("0" + splitStr[0]).substr(-5),
                end: ("0" + splitStr[1]).substr(-5)
            };
        });
        return acc;
    }, {});
    

    var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
    var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
    var start, end;
    var obj = times.reduce((acc, el, idx) => (
        acc[days[idx]] = el.map(timespan => (
            [start, end] = timespan.split("-"), {start, end}
        )), acc
    ), {});
    

    var func = x => x * 2
    
    // is functionally equivalent to:
    
    var func = (function(x)
    {
        return x * 2;
    }).bind(this);
    

    function return function(x){return x;} x=>x

    var arr = [1, 2, 3];
    var first = arr[0];
    var second = arr[1];
    var third = arr[2];
    

    first second third

    var [first, second, third] = [1, 2, 3];
    

    {foo: 1, bar: 2}

    var a = 1;
    var b = 2;
    var obj = {
        a: a,
        b: b
    };
    
    // is functionally equivalent to:
    
    var a = 1;
    var b = 2;
    var obj = {a, b};
    

    {start, end} {start: start, end: end}

    var a = 3; 3 a

    var a = 3 * 2 * 1; 3 * 2 * 1 3 * 2 x * 1 x

    * ++ a++; + a+b; ?: )看起来是这样的: a ? b : c --这有点像 if (a) { b } else { c }

    所以现在了解语句、表达式和运算符之间的区别,我们可以说逗号是 操作人员 它从左到右处理表达式,然后返回最右边的值。所以表达式 a,b,c 将始终评估为 c . 同时表达 var d = (a=1,b=a+1,c=b+1); 会这样评价:

    1. 集合
    2. b
    3. = a=b=c=1
    4. ,
    5. d

    // Implicit return:
    x => x * 2;
    
    // No implicit return:
    x => {
        y += x;
        return x * 2;
    }
    

    x => (
        y += x,
        x * 2
    )
    

    acc[day] = ... , acc

    var obj = times.reduce(
        function(acc, el, idx)
        {
            acc[days[idx]] = el.map(
                function(timespan)
                {
                    var splitStr = timespan.split("-");
                    return {
                        start: ("0" + splitStr[0]).substr(-5),
                        end: ("0" + splitStr[1]).substr(-5)
                    };
                }
            );
            return acc;
        },
        {}
    );
    

    var obj = times.reduce(
        // Arrow function
        (acc, el, idx) =>
        // Instead of {}, we use () with the comma operator
        (
            acc[days[idx]] = el.map(
                // Arrow function
                timespan =>
                // Instead of {}, we use () with the comma operator
                (
                    // Destructuring
                    var [start, end] = timespan.split("-");
                    // Comma operator, return "{start, end}"
                    ,
                    // Enhanced object literal
                    {start, end}
                )
            )
            // Comma operator, returns "acc"
            ,
            acc
        ),
        {}
    );
    

    var start end

    var start, end;
    var obj = times.reduce(
        // ... Lots of stuff
                    [start, end] = el.split("-");
        // ... Lot sof stuff
    );
    

    var start, end;
    var obj = times.reduce((acc, el, idx) => (
        acc[days[idx]] = el.map(timespan => (
            [start, end] = timespan.split("-"), {start, end}
        )), acc
    ), {});
    

    var obj = times.reduce((acc, el, idx) => ({
        ...acc, [days[idx]]: el
    }), {});
    
    // is functionally equivalent to:
    
    var obj = times.reduce((acc, el, idx) => {
        acc[days[idx]] = el;
        return acc;
    }, {});
    
    // which we used the comma operator to reduce to:
    
    var obj = times.reduce((acc, el, idx) => (
        acc[days[idx]] = el, acc
    ), {});
    

    return acc;

    Map

    var map = new Map(times.map((el, idx) => [days[idx], el]));
    
    // is *kind of the same* (but not identical) as:
    
    var obj = times.reduce((acc, el, idx) => (
        acc[days[idx]] = el, acc
    ), {});
    

    Object fromEntries

    [[key, value], [key, value], ...]
    

    var obj = {...};
    obj.entries();
    

    Object.assign

    var obj = Object.assign({}, [1, 2, 3]);
    console.log(obj);
    // {0: 1, 1: 2, 2: 3}
    

    8:30+12:00 8:30-12:00

    • ["8:30+12:00"]
    • splitStr[0]
    • "0" + splitStr[0] "08:30+12:00"
    • ("08:30+12:00").substr(-5) "12:00"
    • splitStr[1]
    • "0" + splitStr[1] "0"
    • ("0").sustr(-5)
    • {start: "12:00", end: "0"}

    Stringly Typed Variables

    "08:30"

    11:30 + 2:00 = 1:30 PM

        2
  •  4
  •   31piy    6 年前

    var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
    var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    var result = {};
    
    days.forEach((day, index) => {
      result[day] = times[index]
        .map(item => {
          let [start, stop] = item.split('-');
          return {start, stop};
        });
    });
    
    console.log(result);
        3
  •  3
  •   dhilt    6 年前

    Array.prototype.reduce Array.prototype.map

    const data = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
    const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    
    const result = data.reduce((acc, item, index) => { 
      acc[days[index]] = 
        item.map(day => ({ 
          start: day.substr(0, day.indexOf('-')), 
          end: day.substring(day.indexOf('-') + 1)
        }));
      return acc;
     }, {});
    
        4
  •  0
  •   Steven Spungin    6 年前

    let dayNames = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
    
    let times = [
      ["8:30-12:00", "14:00-18:00"],
      ["6:15-9:30", "13:00-16:00", "20:00-23:15"],
      [],
      ["9:00-21:00"],
      ["9:00-21:00"],
      [],
      []
    ]
    
    const res = {}
    for (let i = 0; i < 7; i++) {
      const items = []
      res[dayNames[i]] = items
      times[i].forEach(pair => {
        const parts = pair.split('-')
        items.push({
          start: parts[0],
          end: parts[1]
        })
      })
    }
    console.log(res);