【问题标题】:Object result convert into another object JavaScript对象结果转换为另一个对象 JavaScript
【发布时间】:2023-01-08 17:18:44
【问题描述】:

如何将以下对象转换为以下输出JavaScript?目前我有以下对象。你能建议我吗?

[
    {
        "attrTitle": "color",
        "attrValue": "Green"
    },
    {
        "attrTitle": "size",
        "attrValue": "M"
    },
    {
        "attrTitle": "size",
        "attrValue": "L"
    },
    {
        "attrTitle": "size",
        "attrValue": "S"
    },
    {
        "attrTitle": "color",
        "attrValue": "Red"
    }
]

我期望的输出如下

[
    {
        "attrTitle": "color",
        "attrValue": ["Red", "Green"]
    },
    {
        "attrTitle": "size",
        "attrValue": ["S","L","M"]
    }
]

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:
    const input = [ ... ];
    
    const output = input.reduce((acc, curr) => {
        const existingAttr = acc.find(attr => attr.attrTitle === curr.attrTitle);
        if (existingAttr) {
            existingAttr.attrValue.push(curr.attrValue);
        } else {
            acc.push({
                attrTitle: curr.attrTitle,
                attrValue: [curr.attrValue]
            });
        }
        return acc;
    }, []);
    

    【讨论】:

    • 纯代码答案通常不被认为是高质量的;请解释一下您的代码的作用。 (此外,对于适当数量的属性,由于重复使用 .find,这会很慢。)
    猜你喜欢
    • 2015-01-17
    • 2021-08-14
    • 2017-10-15
    • 2013-02-24
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2012-12-05
    相关资源
    最近更新 更多