根据多个匹配键合并对象-Javascript

时间:2018-10-02 17:42:03

标签: javascript arrays object

我正在努力处理一些看起来微不足道的事情。我有一个对象数组:

const vehicles = [
{
    "sku": "1234",
    "year": "2004",
    "make": "Chevrolet",
    "model": "Avalanche",
},
{
    "sku": "1234",
    "year": "2006",
    "make": "Chevrolet",
    "model": "Avalanche",
},
{
    "sku": "1234",
    "year": "2009",
    "make": "Chevrolet",
    "model": "Silverado 1500",
},
{
    "sku": "1234",
    "year": "2006",
    "make": "Chevrolet",
    "model": "Silverado 1500",
}]

我想在skumakemodel上进行匹配并展平对象,使其最终状态为:

const mutatedVehicles = [
  {
    "sku": "1234",
    "years": ["2004", "2006"],
    "make": "Chevrolet",
    "model": "Avalanche",
  },
  {
    "sku": "1234",
    "years": ["2009", "2006"],
    "make": "Chevrolet",
    "model": "Silverado 1500"
  }]

实际上,我最初是使用字典在Python中进行处理的,但最终更喜欢JS中可用的一些方法。我已经尝试过使用Array.forEach,Object.assign和其他一些方法,但是结果很短。

编辑:我被要求分享我尝试过的一些代码-它是Python,而不是JS,因为这是我最初开始的地方。

def match_props(f, x):
    if f['sku'] == x['sku'] and f['year'] != x['year'] and f['make'] == x['make'] and f['model'] == x['model']:
        return True
    else:
        return False

fitments = [
    {
        "sku": "1234",
        "year": "2004",
        "make": "Chevrolet",
        "model": "Avalanche",
        "drive": "",
    },
    {
        "sku": "1234",
        "year": "2009",
        "make": "Chevrolet",
        "model": "Silverado 1500",
        "drive": "",
    },
    {
        "sku": "1234",
        "year": "2006",
        "make": "Chevrolet",
        "model": "Silverado 1500",
        "drive": "",
    },
]

merged = []

for f1 in fitments:
    pMerge = {}
    for f2 in fitments:
        if match_props(f1, f2):
            pMerge = {
                    "sku": f1['sku'],
                    "make": f1['make'],
                    "model": f1['model'],
                    "drive": f1['drive'],
                    "years": [y for y in [f1['year'], f2['year']]]
            }
        else:
            pMerge = f2
    if pMerge not in merged:
        merged.append(pMerge)


print(merged)

2 个答案:

答案 0 :(得分:5)

使用Array.reduceObject.values

                   import { Injectable } from '@angular/core';
                   import { Http, Headers } from '@angular/http';
                   import { HttpModule } from '@angular/http';

            import 'rxjs/add/operator/map';
            import { elementEventFullName } from '@angular/core/src/view';


           let apiUrl = '';

            @Injectable()
            export class UserProvider {

              userData = {"fullName": "","email": "", "acc_type": 
               "","password": ""};

                data = {

                "email": this.userData.email,
                "Type_Id": this.userData.acc_type,
                "Create_DateTime": "2018-10-02T15:18:10.715Z",
                "password": this.userData.password,
                 "name": this.userData.fullName


                  }


               constructor(public http : Http) {
            console.log('Hello AuthService Provider');
            }
              register(data) {
             return new Promise((resolve, reject) => {
                let headers = new Headers();
              headers.append('Content-Type', 'application/json');

                this.http.post(apiUrl+'Regestier', data, {headers: headers})
                .subscribe(res => {
                resolve(res.json());
                }, (err) => {
                  reject(err);

                 });
                });
                 }

                           }

答案 1 :(得分:2)

尽管此答案与Nikhil Aggarwal的答案相重叠,但足以说明这一点。与其固定关键字段,不如着重于具有多个值的字段(此处仅为year,但很容易扩展到其他字段)。

const collect = (vehicles) => Object.values(vehicles.reduce((vs, v) => {
  const {year, ...veh} = v
  const key = JSON.stringify(veh);
  const vehicle = vs[key] || (vs[key] = {years: [], ...veh})
  vehicle.years.push(year)
  return vs
}, {}))

const vehicles = [{"make": "Chevrolet", "model": "Avalanche", "sku": "1234", "year": "2004"}, {"make": "Chevrolet", "model": "Avalanche", "sku": "1234", "year": "2006"}, {"make": "Chevrolet", "model": "Silverado 1500", "sku": "1234", "year": "2009"}, {"make": "Chevrolet", "model": "Silverado 1500", "sku": "1234", "year": "2006"}]

console.log(collect(vehicles))