JS:将数组缩减为嵌套对象

JS: Reduce array to nested objects

所以我有这个数组

var mapped = [[2016, "October", "Monday", {object}], [2017, "January", "Friday", {object}], [2017, "January", "Wednesday", {object}], [2017, "October", "Monday", {object}]]

我想要完成的是这样的:

[{
    "2016": [{
        "October": [{
            "Monday": [{object}]
        }]
    }],
}, {
    "2017": [{
        "January": [{
            "Friday": [{object}]
        }, {
            "Wednesday": [{object}]
        }]
    }, {
        "October": [{
            "Monday": [{object}]
        }]
    }]
}]

我已经搜索了很长时间,但找不到解决方案。通过使用 reduce,我得到了这样的结果:

[
    2016: [{
        "month": "October"
    }]
],
[
    2017: [{
        "month": "January"
    },
    {
        "month": "January"
    },
    {
        "month": "September"
    }]
]

所以我好像很喜欢什么,但还很遥远......这就是我正在做的事情:

mapped.reduce((years, array) => {

                    years[array[0]] = years[array[0]] || [];

                    years[array[0]].push({
                        month: array[1]
                    })

                    return years;

                }, [])

不完全是您指定的内容,但我觉得以下脚本输出的格式最有用 -- 它只在最深层次生成数组:

const  mapped = [[2016, "October", "Monday", { a: 1 }], [2017, "January", "Friday", { a: 1 }], [2017, "January", "Wednesday", { a: 1 }], [2017, "October", "Monday", { a: 1 }]];
   
const result = mapped.reduce( (acc, [year, month, day, object]) => {
    let curr = acc[year] = acc[year] || {};
    curr = curr[month] = curr[month] || {};
    curr = curr[day] = curr[day] || [];
    curr.push(object);
    return acc;
}, {});

console.log(result);
   
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用数组换行

如果你真的需要包装数组,你可以对之前的结果应用一个额外的递归函数:

const  mapped = [[2016, "October", "Monday", { a: 1 }], [2017, "January", "Friday", { a: 1 }], [2017, "January", "Wednesday", { a: 1 }], [2017, "October", "Monday", { a: 1 }]];
   
const result = mapped.reduce( (acc, [year, month, day, object]) => {
    let curr = acc[year] = acc[year] || {};
    curr = curr[month] = curr[month] || {};
    curr = curr[day] = curr[day] || [];
    curr.push(object);
    return acc;
}, {});

function wrapInArrays(data) {
    return Array.isArray(data) ? data 
        : Object.entries(data).map ( ([key, value]) => {
            return { [key]: wrapInArrays(value) };
        });
}

const wrapped = wrapInArrays(result);
console.log(wrapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

要获得完全相同的结构,您可以尝试以下策略。这将适用于任何级别的嵌套,并将继续构建嵌套对象。请查看示例以了解一般处理的各种嵌套级别。

  • 将每个元素映射到对应的嵌套结构中(Map with reduce)

  • 将映射数组中的每个元素合并到一个对象中以合并所有冗余键

  • 将最终的嵌套对象转换成想要的数组结构。

const mapped = [[2016, "October", "Monday", "Morning", {time: "10AM"}], [2017, "January", "Friday", {object: "OBJECT"}], [2017, "January", "Wednesday", {object: "OBJECT"}], [2017, "October", "Monday", {object: "OBJECT"}]];

// Map all objects to the respective nested structure
const nestedMap = mapped.map(elem => {
  let reversed = [...elem.reverse()];
  let firstElem = reversed.splice(0, 1)[0];
  return reversed.reduce((acc, elem) => {let newAcc = {}; newAcc[elem] = [acc]; return {...newAcc}}, firstElem);
})

// Combine array to form a single object
const nestedObj = nestedMap.reduce((acc, elem) => {
  let firstKey = Object.keys(elem)[0];
  acc[firstKey]
    ?
    acc[firstKey].push(elem[firstKey][0])
    :
    acc[firstKey] = elem[firstKey];
  return acc;
}, {})

// Convert back into the array with each object as element
const nestedFinalArr = Object.keys(nestedObj).map(key => ({[key]: nestedObj[key]}))

console.log(nestedFinalArr);