简体   繁体   English

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

[英]Merging objects based on multiple matching keys - Javascript

I'm struggling with something that seems like it should be trivial. 我正在努力处理似乎不重要的事情。 I have an array of objects: 我有一个对象数组:

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",
}]

I would like to match on sku , make , and model and flatten the objects to have a final state of: 我想在skumakemodel上进行匹配并展平对象,使其最终状态为:

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

I've actually worked with this in Python initially using dictionaries, but ultimately prefer some of the methods available in JS. 实际上,我最初是使用字典在Python中进行处理的,但最终更喜欢JS中可用的一些方法。 I've tried using Array.forEach, Object.assign, and a few other methods and have come up short. 我试过使用Array.forEach,Object.assign和其他一些方法,但结果很简短。

EDIT : I was asked to share some of the code I had tried - it's Python, not JS, as that's where I initially started. 编辑 :我被要求分享我尝试过的一些代码-它是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)

Use Array.reduce and Object.values 使用Array.reduceObject.values

 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"}]; let result = Object.values(vehicles.reduce((a,{sku, year, make, model}) => { let id = sku + "_" + make + "_" + model; if(a[id]) a[id].years.push(year) else a[id] = {sku, make, model, years : [year]} return a; },{})); console.log(result); 

Although this answer overlaps with the one from Nikhil Aggarwal, it is enough different to show it. 尽管此答案与Nikhil Aggarwal的答案相重叠,但足以证明这一点。 Instead of fixing the key fields, it focuses on the ones (here just year , but would be easy to extend to others) that have multiple values. 与其固定关键字段,不如着重于具有多个值的字段(这里只是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)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM