如何使用javascript将对象数组的重复元素组合成一个

时间:2018-01-13 05:51:02

标签: javascript arrays json arrayobject

我不熟悉javascript,我不知道如何搜索这个问题。在这里,我简要解释了我的问题。 下面是我要从中找出数据中类似条目并将它们组合为一个对象的数据。 这是我的数据:

var myArr = [{
        "Company": "Samsung",
        "model": "Galaxy S2",
        "screen_size": "5.5"
    },
    {
        "Company": "Samsung",
        "model": "Galaxy S3",
        "screen_size": "5.5"
    },
    {
        "Company": "Samsung",
        "model": "Galaxy S4",
        "screen_size": "5.5"
    },
    {
        "Company": "Xiaomi",
        "model": "Redmi 2",
        "screen_size": "4.7"
    },
    {
        "Company": "Xiaomi",
        "model": "Redmi 4",
        "screen_size": "5"
    },
    {
        "Company": "Xiaomi",
        "model": "Redmi Note 4",
        "screen_size": "5.5"
    }
]

我想组合数组中的所有重复条目。所以,我对这些数据的结果应该是这样的:

[{
    "Company": "Samsung",
    "models": [{
        "Galaxy S2": {
            "screen_size": "5.5"
        }
    }, {
        "Galaxy S3": {
            "screen_size": "5.6"
        }
    }, {
        "Galaxy S4": {
            "screen_size": "5.7"
        }
    }]
}, {
    "Company": "Xiaomi",
    "models": [{
        "Redmi 2": {
            "screen_size": "4.7"
        }
    }, {
        "Redmi 4": {
            "screen_size": "5"
        }
    }, {
        "Redmi Note 4": {
            "screen_size": "5.5"
        }
    }]
}]

有人,请帮助我。

1 个答案:

答案 0 :(得分:1)

您可以使用对象中array#reduce键上的Company对对象进行分组,并使用Object.values()提取所有值。

var myArr=[{ "Company": "Samsung", "model": "Galaxy S2", "screen_size": "5.5" }, { "Company": "Samsung", "model": "Galaxy S3", "screen_size": "5.5" }, { "Company": "Samsung", "model": "Galaxy S4", "screen_size": "5.5" }, { "Company": "Xiaomi", "model":"Redmi 2", "screen_size": "4.7" }, { "Company": "Xiaomi", "model": "Redmi 4", "screen_size": "5" }, { "Company": "Xiaomi", "model": "Redmi Note 4", "screen_size": "5.5" } ],
    result = Object.values(myArr.reduce((r,o) => {
      r[o.Company] = r[o.Company] || {'Company': o.Company, 'Models' : []};
      r[o.Company]['Models'].push({[o.model]:{'screen_size' : o.screen_size}});
      return r;
    }, {}));

console.log(result);